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.
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.
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;
}
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With