Re: Hex to bin

Jens.Toerring_at_physik.fu-berlin.de
Date: 02/26/04


Date: 26 Feb 2004 19:24:13 GMT

Josh Parker <jcp1217@mail.ecu.edu> wrote:
> What would be the best way to convert Hex to bin?
> I am using this code to convert a Dec to Hex:

> char hexstring[10];
> unsigned int number = 800;
> sprintf(hexstring, "%x", number);

> What would be the next step for me to take? I have to do it from Dec
> to Hex and then from Hex to Binary? Any suggestions would be really
> appreciated. Thank you very much

First of all that's not decimal to hex but what you do there is create
a string representation of the number stored in memory (in whatever
respresentation the machine likes, but you can be rather sure that
it's binary;-). You should also be careful, ints could be longer than
9 chars on some machines, in which case you might past the end of the
array for the string!

To get a binary string representation you write your own function,
something like this (but take care, it's completely untested):

char bin_string[ CHAR_BIT * sizeof( unsigned int ) + 1 ];
char *p = bin_string;
unsigned int number = 800;
unsigned int cur = 1 << ( CHAR_BIT * sizeof( unsigned int ) - 1 );

while ( cur )
{
    *p++ = ( number & cur ) ? '1' : '0';
    cur >>= 1;
}
*p = '\0';

Things get a tiny bit more complicted when you don't want leading
zeros, but that shouldn't be too difficult to figure out...

                                       Regards, Jens

-- 
  \   Jens Thoms Toerring  ___  Jens.Toerring@physik.fu-berlin.de
   \__________________________  http://www.toerring.de


Relevant Pages

  • Re: Hex to bin
    ... >>What would be the best way to convert Hex to bin? ... > a string representation of the number stored in memory (in whatever ... Convert the single char in the hex string to some int ...
    (comp.unix.programmer)
  • Re: char[] = "FFFFFF" to 3 unsigned char.
    ... > Each 2 chars from the vector in hex represents a decimal number, ... I used the hex value "abcdef" because it demonstrates the meaning more ...
    (comp.lang.cpp)
  • 16byte "integer" conversion in a decimal representation
    ... I need to convert 16 byte HEX value to a string representation in decimal ... format (output should be 128bit integer, which is not yet supported in ... Delphi). ...
    (borland.public.delphi.non-technical)
  • Re: String to HEX & BIN Conversion?
    ... > salsipius wrote: ... >> I have a char array say ... >> with a space between the 2 HEX numbers that I am trying to read into a ... %x expects unsigned int, which may happen to be the same as ...
    (comp.lang.c)
  • Re: Simple C question...entering binary
    ... Albert van der Horst wrote: ... You can enter the value in hex, octal, or decimal. ...
    (comp.arch.embedded)