Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Thanks in advance

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
Thanks in advance
Posted
Updated 7-May-17 23:05pm
v2

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)
 
Share this answer
 
Comments
Member 12659926 8-May-17 5:09am    
Thanks a lot
Try:
Return Convert.ToString(num, 2).PadLeft(12, "0"C)
 
Share this answer
 
Comments
Member 12659926 8-May-17 5:09am    
Thanks a lot
OriginalGriff 8-May-17 5:42am    
You're welcome!
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)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900