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"

1
  • Why do it character by character instead of just Convert.ToString(Convert.ToInt32(hexDataReadFromTag, 16), 2)? Commented Oct 26, 2016 at 16:03

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.