Convert from string to binary in VB.NET
17,580
Solution 1
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
Solution 2
Let s
be the input string with value A3C0, output
be a variable to store the output.
loop will iterate each letter in the input and store it in the temporary variable temp
. Now see the code:
Dim s As String = "A3C0"
Dim output As String = ""
Dim temp As String = ""
For i As Integer = 1 To Len(s)
temp = Mid(s, i, 1)
output = output & System.Convert.ToString(Asc(temp), 2).PadLeft(4, "0")
' converting each letter into corresponding binary value
'concatenate it with the output to get the final output
Next
MsgBox(output)' display the binary equivalent of the input `s`
Dim array() As Char = output.ToArray()' convert the binary string to binary array
Hope that this is actually you are expected.
Related videos on Youtube
Author by
baraa
Updated on June 04, 2022Comments
-
baraa almost 2 years
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?
-
baraa over 9 yearsActually I want to convert the number from Hex to binary, and I think you convert it from ASCII to binary. Anyways thanks for your help
-
Revolucion for Monica almost 8 yearsGreat! But what is NumberStyles? Shouldn't it be declared?
-
Pradeep Kumar almost 8 years@Marine1, NumberStyles is an Enum and HexNumber is one of the members inside it. It is already declared. You can just simply use it.
-
Herb over 6 years@Marine1, Pradeep is not correct. It requires
System.Globalization
.