15,877,103 members
See more:
hi,
i am converting a hex value to its binary equivalent,using the below function
here i am facing one problem,
i am converting a hex value ex.:0A8 it binary equivalent is 10101000
but i want the output as 000010101000.
i want all twelve bits to get displayed.

ex.:050
i want the above value as 000001010000
kindly provide me the solution
the function i have used to convert from hex to binary
Function HexStringToBinary(ByVal hexString As String) As String
Dim num As Integer = Integer.Parse(hexString, Globalization.NumberStyles.HexNumber)
Return Convert.ToString(num, 2)
End Function

as i am counting the number of bits,i need all bits

What I have tried:

```i am converting a hex value to its binary equivalent,using the below function
here i am facing one problem,
i am converting a hex value ex.:0A8 it binary equivalent is 10101000
but i want the output as 000010101000.
i want all twelve bits to get displayed.

ex.:050
i want the above value as 000001010000
kindly provide me the solution
the function i have used to convert from hex to binary
Function HexStringToBinary(ByVal hexString As String) As String
Dim num As Integer = Integer.Parse(hexString, Globalization.NumberStyles.HexNumber)
Return Convert.ToString(num, 2)
End Function
Posted
Updated 7-May-17 23:05pm
v2

Solution 1

See the String.PadLeft Method (Int32, Char) (System)[^].

In your case for 12 binary digits:
VB
`Return Convert.ToString(num, 2).PadLeft(12, "0"c)`

Member 12659926 8-May-17 5:09am
Thanks a lot

Solution 2

Try:
`Return Convert.ToString(num, 2).PadLeft(12, "0"C)`

Member 12659926 8-May-17 5:09am
Thanks a lot
OriginalGriff 8-May-17 5:42am
You're welcome!

Solution 3

Just to improve on other solutions, to support different length of hex string (as long as it's not larger then max int):

VB
`Return Convert.ToString(num, 2).PadLeft(hexString.Trim().Length * 4, "0"c)`