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 *.
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 *.
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
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
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I apologize.
ASKER