Search code examples
c++chexieee-754

IEEE float hex 424ce027 to float?


If I have a IEEE float hex 424ce027, how do I convert it to decimal?

unsigned char ptr[] = {0x42,0x4c,0xe0,0x27};

how do ?

float tmp = 51.218899;


Solution

  • Perhaps...

    float f = *reinterpret_cast<float*>(ptr);
    

    Although on my x86 machine here I had to also reverse the byte order of the character to get the value you wanted.

    std::reverse(ptr, ptr + 4);
    float f = *reinterpret_cast<float*>(ptr);
    

    You might want to use sizeof(float) instead of 4 or some other way to get the size. You might want to reverse a copy of the bytes, not the original. It's somewhat ugly however you do it.

    edit: As pointed out in the comments, this code is unsafe as it creates two pointers aliasing the same memory but of different types. It may well work on a specific compiler & program, but isn't guarenteed to by the standard.