0

I am new to C#. Please help me with below case

I am trying to convert Hex string to Binary string with 1's and 0's. I tried below method. The problem I am facing here is, if the hex value is 0, the conversion is just 0 instead of "0000". I want the binary string to contain all the 4 bits of the hex value.

const string hexDataReadFromTag= "FF001"  
foreach (char c in hexDataReadFromTag.ToCharArray())
            {
                binaryData.Append(Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2));
}

output obtained is "11111111001" instead of "11111111000000000001"

sunshine
  • 39
  • 2
  • 8
  • Why do it character by character instead of just `Convert.ToString(Convert.ToInt32(hexDataReadFromTag, 16), 2)`? – juharr Oct 26 '16 at 16:03

1 Answers1

1

Use .PadLeft(4, '0') to ensure each hexadecimal digit converts to 4 binary digits (3 to 0011 and not 11):

Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')
Uriel
  • 15,579
  • 6
  • 25
  • 46