Binary 2 Hex

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

ron

Hi,
I am having some issues converting a binary string value
to a hex string value.

Example:
string mybinary = "0000111111111000";
string myhex = Convert.ToString(Convert.ToInt32(mybinary,
2), 16);

returns: "FF8"
should return: "0FF8"

I always need it to return a 16 bit value how do i keep
it from dropping the "0" value's in the hex string?

Thanks,
Ron
 
ron said:
Thought of that, but what if i have the following values.

"1111000011110000" or "0000111100000000" and so on etc..
I need it to be a 16 bit value my string values are 16
bit and i need to look at all 4 positions of the hex
string.

So what would be wrong with left-padding with 0s? The only reason it's
coming up with FF8 instead of 0FF8 is because it's *not* left-padding
it automatically, and 0FF8 is the same as FF8. Left-pad the result to
the size you need (ie 4) and you should be fine.
 
1111000011110000 is 0xF0F0 and
0000111100000000 is 0xF00
both cases would work just fine if you left-pad it with zeroes., I don't
mean you always pad it with one zero, just left-pad with (4-strlen(str))n
zeroes and it should work fine.
 
Daniel Gustafsson said:
1111000011110000 is 0xF0F0 and
0000111100000000 is 0xF00
both cases would work just fine if you left-pad it with zeroes., I don't
mean you always pad it with one zero, just left-pad with (4-strlen(str))n
zeroes and it should work fine.

Or do it slightly more simply:

string myHex = String.Format ("{0:X4}", Convert.ToInt32(myBinary, 2));
 
Back
Top