开发者

Converting float to 32-bit hexadecimal 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.

Chee开发者_如何学Gors.


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].


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


you could use a 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 this vice-versa, too.


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

For example,

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜