2

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?

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

Great! But what is NumberStyles? Shouldn't it be declared?
@Marine1, NumberStyles is an Enum and HexNumber is one of the members inside it. It is already declared. You can just simply use it.
@Marine1, Pradeep is not correct. It requires System.Globalization.
1

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.

1 Comment

Actually 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.