convert int to float to hex

Steller picture Steller · Jan 20, 2010 · Viewed 12.3k times · Source

Using scanf, each number typed in, i would like my program to print out two lines: for example

byte order: little-endian

> 2
     2 0x00000002
  2.00 0x40000000

> -2
    -2 0xFFFFFFFE
 -2.00 0xC0000000

I can get it to print out the 2 in hex but i also need a float and of course i cant scanf as one when i need to also scan as an int

If i cast as a float when i try to printf i get a zero. If i scan in as a float i get the correct output. I have tried to convert the int to a float but it still comes out as zero.

here is my output so far

Int - float - hex

byte order: little-endian

>2

         2  0x000002
      2.00  00000000

it looks like i am converting to a float fine why wont it print as a hex? if i scan in as a float i get the correct hex representation like the first example. this should be something simple. i do need to scan in as a decimal keep in mind i am running this in cygwin

here is what i have so far..

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{


int HexNumber;
    float convert;
printf("Int - float - hex\n");



int a = 0x12345678;
unsigned char *c = (unsigned char*)(&a);
if (*c == 0x78)
{
    printf("\nbyte order: little-endian\n");
}
else
{
    printf("\nbyte order: big-endian\n");
}

printf("\n>");
scanf("%d", &HexNumber);
printf("\n%10d  ",HexNumber);
printf("%#08x",HexNumber);





convert =  (float)HexNumber; // converts but prints a zero

printf("\n%10.2f  ", convert); 
printf("%#08x", convert); // prints zeros


return 0;
}

Answer

Michael Buen picture Michael Buen · Jan 20, 2010

try this:

int i = 2;
float f = (float)i;
printf("%#08X", *( (int*) &f ));

[EDIT]

@Corey:

let's parse it from inside out:

&  f = address of f = say address 0x5ca1ab1e
(int*)  &f = interpret the address 0x5ca1ab1e as integer pointer
*  ((int*)&f) = get the integer at address 0x5ca1ab1e

the following is more concise, but it's hard to remember the C language's operator associativity and operator precedence(i prefer the extra clarity of some added parenthesis and whitespace provides):

printf("%#08X", *(int*)&f);