Convert float to 32-bit C ++ hexadecimal

Can someone tell me if there is any code to convert floating point number to hexadecimal format?

For Ex: float num = 70.482 and the hexadecimal function should return 428CF6C9.

If there are any codes already made before then, contact me.

Greetings.

+5
source share
6 answers

something like the floathohex transform I'm using .. (it also does bit-swap if you don't need to take it out)

CString Class::FloatToHex(float* yourfloat)
{
unsigned char ch[4];
Cstring output;

memcpy(ch,yourfloat,sizeof(float));
output.Format("%X%X%X%X",ch[3],ch[2],ch[1],ch[0]);

return output;
}
+2
source

You can simply trivially write this yourself:

float x;
const unsigned char * pf = reinterpret_cast<const unsigned char*>(&x);

for (size_t i = 0; i != sizeof(float); ++i)
{
  // ith byte is pf[i]
  // e.g. printf("0x02X ", pf[i]);
}

In fact, you can do this to get a binary representation of any variable (standard-layout *).

*) , @R. !

long double (, , 80- ), , 10 , 12 16 x86/x64 .

+15

:

union float_bits {
    unsigned int i;
    float f;
} bits;

bits.f, bits.i. , , , float int. , , float.

:

float f;
char *c = (char *) &f;

f c[index].

+2
float f = 70.482f;
int i = *(reinterpret_cast<int*>(&f));
printf("%08x\n", i);
+1
source

you can use union:

union FloatToChar {
    float f;
    char  c[sizeof(float)];
};

FloatToChar x;
x.f = 10.42f;
for (size_t i=0; i<sizeof(float); i++)
    printf( "%X", x.c[i] );

you could do it too.

+1
source

Just use sprintf (): http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

For instance,

char out[8];
float myFloat = 70.482;
sprintf(out,"%X",myFloat);
0
source

All Articles