Change Hex to Binary

  • Thread starter Thread starter ron
  • Start date Start date
R

ron

Hi,
I have a 16 bit hex value contained in a string.
example="00A4"
I need to convert the hex value to binary.
I then need to return the whole binary value as a string.
example="0000000010100100"

Then need to look at each bit value to see if "1" or "0"
and return a bool indicating the resultant.

I have done this in VB6 but it was a long drawn out
process of if statements.

There must be a easy way do this in C#?

Could someone please explain what is the best way to
handle this, a code example would be most appreciated.

Thanks Ron
 
ron said:
I have a 16 bit hex value contained in a string.
example="00A4"
I need to convert the hex value to binary.
I then need to return the whole binary value as a string.
example="0000000010100100"

Then need to look at each bit value to see if "1" or "0"
and return a bool indicating the resultant.

I have done this in VB6 but it was a long drawn out
process of if statements.

There must be a easy way do this in C#?

Could someone please explain what is the best way to
handle this, a code example would be most appreciated.

example = Convert.ToString(Convert.ToInt32(example, 16), 2);

Note that it's using a 32 bit int instead of 16 bits to avoid problems
with values > 32768.

That doesn't end up with any left padding either, but that's easy
enough to do as well.
 
William Stacey said:
string binaryText = Convert.ToString(Convert.ToInt32(hex, 16),
2).PadLeft(8,0);

Cheers - hadn't seen PadLeft before. I think the arguments in question
should be (16, '0') though :)
 
Back
Top