Convert string of byte array back to original string in vb.net - 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

Related

Get first three bits from a byte

My question is simple, i need to convert the first three bits of a byte to a integer (Enum) value. However the things i try i always get a 0 back. This is wat the document says:
Bit 0-3: These bits indicate the connection state.
Value 0 to 14 indicate the connection state. Value 3 = Connected
Now the response i get (from a serial device) is a encoded byte stream of ASCII hex values, so i first need to convert it from a hex string to byte array and then get the bits from it. This is my code so far:
Dim strResonse As String = "0C03" 'This should result in a connection state value of 3
Dim ConState(2) As Byte
ConState = HexStringToByteArray(strResonse)
Dim int As Integer = ConState(1) << 1 And ConState(1) << 2 And ConState(1) << 3
Debug.Print(int.ToString)
Private Function HexStringToByteArray(ByVal shex As String) As Byte()
Dim B As Byte() = Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
Return Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
End Function
It would be easier to use bit operation
Dim connectionState As Integer
Dim response As Integer = &HC03
' Get the first 4 bits. 15 in binary is 1111
connectionState = response And 15
If your input is really a string, there a built-in way to convert to integer.
Dim response As Integer = Convert.ToInt32("C03", 16)
If you really want to get an array, I suggest you use the built in method.
Dim allBits As Byte() = BitConverter.GetBytes(response)
There also the BitArray class that can be handy.

Convert Arabic string to an array of bytes

I have a function which converts string to an array of bytes. If the string is written in English, the function works fine. But if the input string is Arabic, the function doesn't return, and I get this error:
Value was either too large or too small for an unsigned byte
Friend Function StringtoByteArray(ByRef value As String) As Byte()
Dim temp() As Byte
ReDim temp(Len(value) - 1)
Dim i As Integer
For i = 0 To Len(value) - 1 Step 1
temp(i) = Convert.ToByte(Convert.ToChar(Mid(value, i + 1, 1)))
Next
StringtoByteArray = temp
End Function
What should I change to convert Arabic characters to byte?
I am using VB.NET.
You don't need to write your function for that, this should work:
Dim b As Byte() = System.Text.Encoding.Unicode.GetBytes(value)

Convert string from Base2 to Base4

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.

String Manipulation To Get An Item In The Middle Of A CSV File

I have a csv file I need to parse and get an item out of the middle of it. I have chose string manipulation to do this.
sample input file data would be..
Nick,frog,snake,1234
I can get the last entry "1234" with this code..
line.Substring(line.LastIndexOf(",") + 1)
How would I get the 3rd entry, "snake", with substrings? (what the OP means is: how can I get the third element in the comma-separated string, which happens to be "snake")
If you've stored the text of your file in myInputText, and you want to access the third item, the following will work:
resultString = Strings.Split(myInputText, ",")(2)
You can access any string in the file this way.
How would I get the 3rd entry "snake" with substrings?
The easiest way would obviously be with split:
Dim teststr As String = "Nick,frog,snake,1234"
Dim teststr2 As String = teststr.Split(","c)(2)
A simple function like this, using substring, will do the same thing:
Dim teststr3 As String = GetStr(teststr, 2)
Private Function GetStr(input As String, index As Integer) As String
input += ","
Dim counter As Integer = 0
If index <> 0 Then
Do
input = input.Substring(input.IndexOf(","c)).TrimStart(","c)
counter += 1
Loop Until counter = index
End If
GetStr = input.Substring(0, input.IndexOf(","c))
End Function

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.