September 28th, 2003, 02:34 PM
C : How to output bit representation in hexadecimal?
How do I write a program in C that accepts a floating-point input and output it's bits representation in hexadecimal?
September 28th, 2003, 03:02 PM
Take a pointer to the float, cast it to a char pointer and print each character as a two digit hex value. Something like this.
Change float to double as necessary.
void float_to_hex( float val )
char* float_byte_array = (char*)&val ;
size_t i ;
printf( "%d\n",sizeof(float) );
printf( "0x" ) ;
for( i = 0; i < sizeof( float ); i++ )
printf( "%2.2X", float_byte_array[i] ) ;
September 28th, 2003, 03:40 PM
Thank you very much for the speedy reply, sir.
It is running perfectly fine!
May I know what is "%x" and "size_t i"?
September 28th, 2003, 03:45 PM
size_t is the defined type that is returned by sizeof. It normally translates to int or short int.
%x is the format descriptor of hexadecimal. All numbers are stored internally as binary. %d displays a number as decimal. %o as octal. %x as hex (unsigned is implied). Read the man page or help file on printf for more details.
September 28th, 2003, 03:55 PM
Thank you, kind sir.
Do u happen to know assembly too?
September 28th, 2003, 04:16 PM
did someone say asm? :D sorry to interject but i love assembly programming; what are you trying to do?
September 28th, 2003, 05:08 PM
Your reply is god-sent.....
Both has to be written in MIPS
1) I need to perform an addition for 2 64bit integer using 32bit registers.
2) Multiply a small value by 5times using shift and add while ignoring overflow.
Thanx a milion!!!
September 28th, 2003, 05:51 PM
hmm smells like someone is cooking some fresh homework on the grill and i just ate some pizza; sorry ;) . also i am unfamiliar with MIPS, but i am reading some stuff i found on google directly related to your assignment.... so happy googling :D
September 28th, 2003, 06:14 PM
September 29th, 2003, 03:36 AM
In GCC it is "unsigned int". Originally I declared i as int and got a signed/unsigned comparison warning for the 'for' expression, so I changed type of i to agree with the result of sizeof.
September 29th, 2003, 03:40 AM
dwise1_aol already answered this, however note that my code used "%X" rather than "%x", so that the digits A...F are displayed in uppercase rather than lowercase - choose whichever you prefer.
September 29th, 2003, 03:14 PM
Thank you very much for following it up.
The detail explanation of usage of size_t & int is very useful to me.
I appreciate it much.