Change byte array to integer in VB.net - vb.net

I have a byte array need to convert to integer, and this array only have one value. I tried Bitconverter, convert.ToInt32 both are not working for me. my code as follows:
Dim a As new Byte() ={&H1C} ' the value range is {&H01} to {&HFF}
Dim key As integer = BitConverter.ToInt32(a,1)
I need the result with key = 28, which convert function I should use?
Thank you very much.

BitConverter.ToInt32 needs 4 bytes to work with, so you just need to put your one byte value into a 4 byte array. Allowing for the endianness, something like this:
Dim a() As Byte = { &H1C }
Dim b(3) As Byte
If BitConverter.IsLittleEndian Then
b(0) = a(0)
Else
b(3) = a(0)
End If
Dim key As Integer = BitConverter.ToInt32(b, 0)

You are not converting an array of values, but rather a single array element.
That said, there is no need to call a conversion function to convert a single Byte to an Integer. Just assign the value.
Dim key As Integer = a(0)

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.

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.

How to replace bytes in VB.NET?

I have two strings:
Dim Original_Hex_Bytes as string = "616572646E61"
Dim Patched_Hex_Bytes as string = "616E64726561"
Then I have a binary file and I need to search for the Original_Hex_Bytes and replace them with Patched_Hex_Bytes; I don't konw the offset where begin to write new bytes :(
How can I do this?
If needed, I also know how to convert Hex strings in bytes, I use this:
Private Function Hex_To_Bytes(ByVal strinput As String) As Byte()
Dim i As Integer = 0
Dim x As Integer = 0
Dim bytes(strinput.Length / 2) As Byte
Do While (strinput.Length > i + 1)
Dim lngDecimal As Long = Convert.ToInt32(strinput.Substring(i, 2), 16)
bytes(x) = Convert.ToByte(lngDecimal)
i += 2
x += 1
Loop
Return bytes
End Function
You can use BinaryReader and BinaryWriter classes to achieve this.
But in this case, as you do not know the file structure, need to read the entire file and sweep it in search of bytes array and will be easier to use ASCII strings as aerdna and andrea.
When you know the structure of a file is more appropriate to work with data structure to manipulate its contents.

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

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)