Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float to 32-bit hexadecimal C++

Tags:

c++

visual-c++

Could anyone please tell me if there is any code to convert floating point number to hexadecimal format?

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

If there are any codes already done before on this, kindly link me.

Cheers.

like image 672
Neophile Avatar asked Aug 30 '11 15:08

Neophile


3 Answers

You can just trivially write that 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 that to obtain the binary representation of any (standard-layout*) variable.

*) thanks, @R. Martinho Fernandes!

If you decide to try this on a long double (or rather, an 80-bit extended precision float), beware that that has only 10 bytes, but is padded to 12 or 16 on x86/x64, respectively.

like image 133
Kerrek SB Avatar answered Oct 07 '22 17:10

Kerrek SB


something like this is the floattohex conversion i use.. (it also performs a bit swap, if you dont need this 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;
}
like image 37
Michael Avatar answered Oct 07 '22 15:10

Michael


Consider:

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

Assign the floating point number into bits.f, and then interpret the whole number as an unsigned integer and read it with bits.i. By doing this the floating point representation bytes will stay intact, and no implicit type conversion will be done as it would be when assigning a float to an int type variable. In this case we assume that the size of integer is same as the size of float.

Or you can do:

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

And then access the individual bytes of f through c[index].

like image 23
phoxis Avatar answered Oct 07 '22 17:10

phoxis