Convert string from Base2 to Base4 - vb.net

I wish to convert text to base 4 (AGCT), by first converting it to binary (I've done this bit) and then break it into 2 bit pairs.
can someone help me turn this into code using vb.net syntax?
if (length of binary String is an odd number) add a zero to the front (leftmost position) of the String. Create an empty String to add translated digits to. While the original String of binary is not empty { Translate the first two digits only of the binary String into a base-4 digit, and add this digit to the end (rightmost) index of the new String. After this, remove the same two digits from the binary string and repeat if it is not empty. }
in this context:
Dim Base2Convert As String = ""
For Each C As Char In Result.Text
Dim s As String = System.Convert.ToString(AscW(C), 2).PadLeft(8, "0")
Base2Convert &= s
Next
Result.Text = Base2Convert
Dim Base4Convert As String = ""
For Each C As Char In Result.Text
'//<ADD THE STATEMENT ABOVE AS CODE HERE>//
Base4Convert &= s
Next
Result.Text = Base4Convert

.NET does not support conversion to non-standard base, such as 4, so this will not work:
Dim base4number As String = Convert.ToString(base10number, 4)
From MSDN:
[...] base of the return value [...] must be 2, 8, 10, or 16.
But you can write your own conversion function, or take the existing one off the web:
Public Function IntToStringFast(value As Integer, baseChars As Char()) As String
Dim i As Integer = 32
Dim buffer(i - 1) As Char
Dim targetBase As Integer = baseChars.Length
Do
buffer(System.Threading.Interlocked.Decrement(i)) =
baseChars(value Mod targetBase)
value = value \ targetBase
Loop While value > 0
Dim result As Char() = New Char(32 - i - 1) {}
Array.Copy(buffer, i, result, 0, 32 - i)
Return New String(result)
End Function
Used this answer. Converted with developer fusion from C# + minor adjustments. Example:
Dim base2number As String = "11110" 'Decimal 30
Dim base10number As Integer = Convert.ToInt32(base2number, 2)
Dim base4number As String = IntToStringFast(base10number, "0123")
Console.WriteLine(base4number) 'outputs 132
Notice that you don't need base 2 there as an intermediate value, you can convert directly from base 10. If in doubt, whether it worked correctly or not, here is a useful resource:
Number base converter

Converting the number to base first and then to base 4 doesn’t make a lot of sense, since directly converting to base 4 is the same algorithm anyway. In fact, representation of a number in any base requires the same general algorithm:
Public Shared Function Representation(number As Integer, digits As String) As String
Dim result = ""
Dim b = digits.Length
Do
result = digits(number Mod b) & result
number \= b
Loop While number > 0
Return result
End Function
Now you can verify that Representation(i, decimal) does the same as i.ToString():
Dim decimalDigits = "0123456789"
For i = 0 To 30 Step 3
Console.WriteLine("{0}, {1}", i.ToString(), Representation(i, decimalDigits))
Next
It’s worth noting that i.ToString() converts i to decimal base because this is the base we, humans, are mostly using. But there is nothing special about decimal, and in fact internally, i is not a decimal number: its representation in computer memory is binary.
For conversion to any other base, just pass a different set of digits to the method. In your case, that’d be "ACGT":
Console.WriteLine(Representation(i, "ACGT"))
Hexadecimal also works:
Console.WriteLine(Representation(i, "0123456789ABCDEF"))
And, just to repeat it because it’s such a nice mathematical property: so does any other base with at least two distinct digits.

Related

Parsing binary to BigInteger in VB .NET?

How are you?
I wrote a program manipulating big binary chains (string variables). This said manipulation requires me to store my chains in a variable so I can use them as numbers. The only variable type that I have found big enough to store such lengthy numbers is BigInteger (we are talking 1.0E100+).
I would like to use something like:
val = BigInteger.Parse(bin, 2)
But the second parameter needed is a NumberStyles object, which can only refer to a NumberStyles.HexNumber.
Is there a simple/optimal way to do this?
Thank you very much. :)
This converts a binary string to BigInteger in 8 bit chunks. It assumes that the binary string represents a positive number.
Private Function BinToBI(ByRef binstr As String) As BigInteger
Dim t As New List(Of Byte)
Dim s As String
Dim idx As Integer = binstr.Length
Do While idx > 0
'get 8 bits
If idx >= 8 Then
s = binstr.Substring(idx - 8, 8)
Else
s = binstr.Substring(0, idx).PadLeft(8, "0"c)
End If
'convert to byte and add to list
Dim b As Byte = Convert.ToByte(s, 2)
t.Add(b)
idx -= 8
Loop
'force to positive
If t(t.Count - 1) >= 128 Then
t.Add(0)
End If
Dim rv As New BigInteger(t.ToArray)
Return rv
End Function
for testing
Dim d As Double = 1.0E+101
Debug.WriteLine(d.ToString("n2"))
Dim bi As BigInteger
' Dim bin As String = "1111111111111111111111111111111" 'Integer.MaxValue
' Dim bin As String = "111111111111111111111111111111111111111111111111111111111111111" 'Long.MaxValue
Dim bin As String = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110"
bi = BinToBI(bin)
Debug.WriteLine(bi.ToString("n2"))
This was not well tested but should give you some ideas.

Convert Decimal to Ascii?

this is how to convert decimal to Ascii, but i have decimal in defferent format, and i want ot convert it to ascii.
Public Shared Function DecimalToASCII(dec As String) As String
Dim ascii As String = String.Empty
For i As Integer = 0 To dec.Length - 1 Step 3
ascii += CChar(ChrW(Convert.ToByte(dec.Substring(i, 3))))
Next
Return ascii
End Function
EX:
This is in Decimal and i want ot input it in textbox1.text:
"912,697,583,1065,261"
and i want to do operation to each group of numbers between comma and then convert it to Ascii???
To split the string into groups, you can just use the Split command. Your code is a long winded way of doing this - although it will fall over when it tries to deal with the four digit number.
Create a string array with no predefined number of elements like this -
Dim myArray()
Populate it with this code
myArray = Split (dec,",")
So now, using your input example, your ascii string array contains this data
myArray (0) = "912"
myArray (1) = "697"
myArray (2) = "583"
myArray (3) = "1065"
myArray (4) = "261"
If you want to have numbers that you can use in arithmetic operations, use this code instead. The function assumes that you're using integers, but if you want to use another type, just change all the occurrences of Integer to the type you want to handle, and change the CInt function to CDbl or cSng.
Public Shared Function DecimalToASCII(dec As String) As Integer()
'create an array of strings
Dim ascii() As String
'split each group into the array
ascii = Split(dec, ",")
'declare numbers array that is the same size as the ascii array
Dim numbers(ascii.GetUpperBound(0)) As Integer
'convert the array of strings to an array of numbers
For i As Integer = 0 To ascii.GetUpperBound(0) - 1
numbers(i) = CInt(ascii(i))
Next
'return an array of numbers containing each group
Return numbers
End Function
Use it like this
Dim dec As String = "912,697,583,1065,261"
Dim MyNumbersArray() As Integer = DecimalToASCII(dec)
With this code, you will have an array of Integers like this
MyNumbersArray(0) = 912
MyNumbersArray(1) = 697
MyNumbersArray(2) = 583
MyNumbersArray(3) = 1065
MyNumbersArray(4) = 261
Now you can perform whatever math you want using the array elements.

Convert string of byte array back to original string in vb.net

I have a plain text string that I'm converting to a byte array and then to a string and storing in a database.
Here is how I'm doing it:
Dim b As Byte() = System.Text.Encoding.UTF8.GetBytes("Hello")
Dim s As String = BitConverter.ToString(b).Replace("-", "")
Afterwards I store the value of s (which is "48656C6C6F") into a database.
Later on, I want to retrieve this value from the database and convert it back to "Hello". How would I do that?
You can call the following function with your hex string and get "Hello" returned to you. Note that the function doesn't validate the input, you would need to add validation unless you can be sure the input is valid.
Private Function HexToString(ByVal hex As String) As String
Dim result As String = ""
For i As integer = 0 To hex.Length - 1 Step 2
Dim num As Integer = Convert.ToInt32(hex.Substring(i, 2), 16)
result &= Chr(num)
Next
Return result
End Function
James Thorpe points out in his comment that it would be more appropriate to use Encoding.UTF8.GetString to convert back to a string as that is the reverse of the method used to create the hex string in the first place. I agree, but as my original answer was already accepted, I hesitate to change it, so I am adding an alternative version. The note about validation of input being skipped still applies.
Private Function HexToString(ByVal hex As String) As String
Dim bytes(hex.Length \ 2 - 1) As Byte
For i As Integer = 0 To hex.Length - 1 Step 2
bytes(i \ 2) = Byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber)
Next
Return System.Text.Encoding.UTF8.GetString(bytes)
End Function

how to get value by split in vb.net 2005

i have a database in one field like below 222-225. I try to make split to read that value for my function. Just simple function a=225 b=222 then total=(a-b)+1. here my code
Dgv.CellClick
'Dim x As Boolean
Dim a As Double
Dim total As Double
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
Split(a, "-")
total = (a) - (a)
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
My problem is this doesn't work. I can't get the value that I split. Any idea how to solve this problem?
note: I use VB.NET 2005
If you want total=(a-b)+1 .. That should be
dim b = a.Split("-")
total = val(b(1)) - val(b(2)) + 1
may be this can help. try this...
Dim a As String
a = ""
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString
Dim ary() As String
x = a
ary = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Like others have said, Split() returns a String array, like this:
Dim SplitValue() As String = Split(a, "-")
total = (CType(SplitValue(1), Double) - CType(SplitValue(0), Double)) + 1
If I read your question correctly, the value you're looking for is 222-225, and that value is located in the specified cell of Dgv (which I'm guessing is a DataGridView). If my understanding is correct, there are a couple of things going on.
First, I'm not sure why you're trying to convert that value to a double with the following line of code:
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
The Item property of a DataGridView holds a DataGridViewCell, and the Value property of the DataGridViewCell returns an Object. Trying to convert 222-225 to a double will, I believe, fail (though since this is VB.NET, it's possible it won't depending on the options you set - I'm not as familiar with VB.NET as I am with C#).
Even if it does successfully work (I'm not sure what the output would be), Split expects a string. I would change that line of code to the following:
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
Now you have a string that you can use Split on. The Split you have in your posted code appears to be the Visual Basic (pre-.NET) Split method Split Function (Visual Basic). As others have mentioned, Split returns an array of strings based on the delimiter. In your code, you don't assign the result of Split to anything, so you have no way to get the values.
I would recommend using the .NET version of Split (String.Split Method) - there are several ways you can call String.Split, but for purposes of your code I'd use it like this:
Dim splits As String() = a.Split(New Char() { "-" })
Where a is the string value from the selected DataGridViewCell above. This will give you a 2-element array:
splits(0) = "222"
splits(1) = "225"
The final part is your formula. Since you have strings, you'll need to convert them to a numeric data type:
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Which becomes (225 - 222) + 1 = 4.
Putting it altogether it would look something like this:
Dim a As String
Dim total As Double
Dim splits() As String
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
splits = a.Split(New Char() { "-" })
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Split returns an array. something like this. VB.Net is not my primary language but this should help.
dim arr = a.Split(New Char (){"-"})
total = ctype(arr(0), double) - ctype(arr(1),double)
Try this:
Dim aux() As String = a.Split("-"c)
total = CDbl(aux(0)) - CDbl(aux(1)) + 1
Dim a As string
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value
Dim ary() As String
x = a
ary() = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total

Mixed Encoding to String

I have a string in VB.net that may contain something like the following:
This is a 0x000020AC symbol
This is the UTF-32 encoding for the Euro Symbol according to this article http://www.fileformat.info/info/unicode/char/20ac/index.htm
I'd like to convert this into
This is a € symbol
I've tried using UnicodeEncoding() class in VB.net (Framework 2.0, as I'm modifying a legacy application)
When I use this class to encode, and then decode I still get back the original string.
I expected that the UnicodeEncoding would recognise the already encoded part and not encode it against. But it appears to not be the case.
I'm a little lost now as to how I can convert a mixed encoded string into a normal string.
Background: When saving an Excel spreadsheet as CSV, anything outside of the ascii range gets converted to ?. So my idea is that if I can get my client to search/replace a few characters, such as the Euro symbol, into an encoded string such as 0x000020AC. Then I was hoping to convert those encoded parts back into the real symbols before I insert to a SQL database.
I've tried a function such as
Public Function Decode(ByVal s As String) As String
Dim uni As New UnicodeEncoding()
Dim encodedBytes As Byte() = uni.GetBytes(s)
Dim output As String = ""
output = uni.GetString(encodedBytes)
Return output
End Function
Which was based on the examples on the MSDN at http://msdn.microsoft.com/en-us/library/system.text.unicodeencoding.aspx
It could be that I have a complete mis-understanding of how this works in VB.net. In C# I can simply use escaped characters such as "\u20AC". But no such thing exists in VB.net.
Based on advice from Heinzi I implemented a Regex.Replace method using the following code, this appear to work for my examples.
Public Function Decode(ByVal s As String) As String
Dim output As String = ""
Dim sRegex As String = "0x[0-9a-zA-Z]{8}"
Dim r As Regex = New Regex(sRegex)
Dim myEvaluator As MatchEvaluator = New MatchEvaluator(AddressOf HexToString)
output = r.Replace(s, myEvaluator)
Return output
End Function
Public Function HexToString(ByVal hexString As Match) As String
Dim uni As New UnicodeEncoding(True, True)
Dim input As String = hexString.ToString
input = input.Substring(2)
input = input.TrimStart("0"c)
Dim output As String
Dim length As Integer = input.Length
Dim upperBound As Integer = length \ 2
If length Mod 2 = 0 Then
upperBound -= 1
Else
input = "0" & input
End If
Dim bytes(upperBound) As Byte
For i As Integer = 0 To upperBound
bytes(i) = Convert.ToByte(input.Substring(i * 2, 2), 16)
Next
output = uni.GetString(bytes)
Return output
End Function
Have you tried:
Public Function Decode(Byval Coded as string) as string
Return StrConv(Coded, vbUnicode)
End Function
Also, your function is invalid. It takes s as an argument, does a load of stuff and then outputs the s that was put into it instead of the stuff that was processed within it.