Change Hex to Binary

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
 
J

Jon Skeet

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.
 
W

William Stacey

string binaryText = Convert.ToString(Convert.ToInt32(hex, 16),
2).PadLeft(8,0);
 
J

Jon Skeet

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 :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top