baraa baraa - 2 months ago 10
Vb.net Question

Convert from string to binary in VB.NET

Let's say that I have the string "A3C0", and I want to store the binary value of it in a Boolean array.

After the conversion (from string to binary) the result should be = 1010001111000000

Then I want to store it in this array,

dim bits_array(15) as Boolean


at the end:

bits_array(0)=0
bits_array(1)=0
.
.
.
.
bits_array(15)=1


How can I do this?

Answer

It's easy.

Function HexStringToBinary(ByVal hexString As String) As String
    Dim num As Integer = Integer.Parse(hexString, NumberStyles.HexNumber)
    Return Convert.ToString(num, 2)
End Function

Sample Usage:

Dim hexString As String = "A3C0"
Dim binaryString As String = HexStringToBinary(hexString)
MessageBox.Show("Hex: " & hexString & "    Binary: " & binaryString)

To get the binary digits into an array, you can simply do:

Dim binaryDigits = HexStringToBinary(hexString).ToCharArray