469,349 Members | 1,528 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,349 developers. It's quick & easy.

Change Hex to Binary

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
Nov 13 '05 #1
4 33370
ron <goodr@no_spam_4me_mddm.panasonic.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 13 '05 #2
string binaryText = Convert.ToString(Convert.ToInt32(hex, 16),
2).PadLeft(8,0);

That doesn't end up with any left padding either, but that's easy
enough to do as well.

Nov 13 '05 #3
William Stacey <st*****@mvps.org> wrote:
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 :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 13 '05 #4
Cheers :-)
Nov 13 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

27 posts views Thread by Eric | last post: by
3 posts views Thread by Tron Thomas | last post: by
9 posts views Thread by Ching-Lung | last post: by
5 posts views Thread by Charles F McDevitt | last post: by
13 posts views Thread by James Reid | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.