Link to home
Start Free TrialLog in
Avatar of cfans
cfans

asked on

Int to Binary Conversion

I'm looking for a good int to binary conversion using C.
I've searched on here for some of the examples, however didn't find any I really liked..

I'd like to convert an int into a char *.
Avatar of cfans
cfans

ASKER

Is there also a way to just use printf to display an int as a binary number?
Avatar of sunnycoder
This is a very common homework question. May we know why you need this routine?

Also ...
>I've searched on here for some of the examples, however didn't find any I really liked..
What is that you are exactly looking for? Why was the existing code not good enough?

Cheers!
sunnycoder
Avatar of cfans

ASKER

Well actually it isn't that I didn't like it.. I tried using some of the examples.. and they just gave me seg faults.. can't really figure out why either.
An int actually is a binary number already.

You can print it in hexadecimal with:
printf( "%x", intval );
or formatted in C-style and with all 4 bytes present:
printf( "0x%.8x", intval );

to print it to a string use:
char str[ 20 ];
sprintf( str, "0x%.8x", intval );

to get a char* of the 4 bytes of an int you can simply cast the pointer to it
char * barr =  (char *) &intval;
and access the bytes this way:
char firstByte = barr[ 0 ];
but the ordering of the bytes is processor dependant if you do it this way (little/big endian)

to do this processor independant you can use:
char barr[ 4 ];
barr[ 0 ] = (char) ( intval >> 24 );
barr[ 1 ] = (char) ( intval >> 16 );
barr[ 2 ] = (char) ( intval >>  8 );
barr[ 3 ] = (char) intval;

I'm not sure if this is what you meant.
SOLUTION
Avatar of leisner
leisner

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I apologize.