Converting float to 32-bit hexadecimal C++

16,557

Solution 1

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;
}

Solution 2

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.

Solution 3

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

Solution 4

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

Solution 5

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.

Share:
16,557
Neophile
Author by

Neophile

Updated on June 08, 2022

Comments

  • Neophile
    Neophile almost 2 years

    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.

    • Nawaz
      Nawaz over 12 years
      Why 70.482 should return 428CF6C9? What is the logic?
    • Neophile
      Neophile over 12 years
      That's what the online converter returned the value as. babbage.cs.qc.edu/IEEE-754/Decimal.html
    • crashmstr
      crashmstr over 12 years
      Did you look at the JavaScript for that page? You would need to translate to c++, but at least you can look at their algorithm.
  • pezcode
    pezcode over 12 years
    that is assuming sizeof(int) == sizeof(float)
  • Neophile
    Neophile over 12 years
    Yea, we tried that. Did not work the way we wanted it to. Did not return the correct value.
  • Kerrek SB
    Kerrek SB over 12 years
    That's also undefined behaviour.
  • Kerrek SB
    Kerrek SB over 12 years
    Careful: float gets promoted to double when passed through variadic arguments!
  • Praetorian
    Praetorian over 12 years
    +1 And you don't need to worry about long doubles if you're using MSVC :-)
  • R. Martinho Fernandes
    R. Martinho Fernandes over 12 years
    Not any variable though. In C++11 the value is unspecified if either the source or the destination pointer types is not a standard-layout type. I'm pretty sure there's some similar restriction in C++03.
  • phoxis
    phoxis over 12 years
    will the byte ordering of the architecture effect the order of bytes which are printed ?
  • phoxis
    phoxis over 12 years
    @R. Martinho Fernandes: right, i went the c way. corrected now.
  • Kerrek SB
    Kerrek SB over 12 years
    @phoxis: Yes! This will expose all the gory details of the implementation ... padding of structs, most importantly. R. Martinho: What exactly do you mean? Which part of this cast is unspecified?
  • R. Martinho Fernandes
    R. Martinho Fernandes over 12 years
    @Kerrek: not this cast. But you said you could do this to get the binary representation of any variable. You can't for non-standard-layout types.
  • Voo
    Voo over 12 years
    @Kerrek SB While the union example is technically undefined, it's an often used idiom and quite certainly will be supported by any compiler and every other solution is ugly and unhandy. I'd still mention it (and use it myself, bad me) but a warning is certainly in place I agree..
  • Kerrek SB
    Kerrek SB over 12 years
    @R. Martinho: Interesting. Can you give a quick counter example and say what goes wrong?
  • R. Martinho Fernandes
    R. Martinho Fernandes over 12 years
    Well, if A is, for example, a type with a virtual member function and given A a; auto b = reinterpret_cast<const char*>(&a); the value of b is unspecified. It bet in pretty much all implementations you will get to see the vptrs and all that, though. Oh, and the guarantee that you can roundtrip is still valid: auto x = reinterpret_cast<const A*>(b); will give you the original pointer, even though the intermediate value is unspecified.
  • Mooing Duck
    Mooing Duck over 12 years
    @Kerrek: What is the subtlety that allows the casting to const unsigned char that you did, and not int? (I believe you, I just don't see it)
  • Kerrek SB
    Kerrek SB over 12 years
    The difference is that casting to char is allowed, but casting to other types isn't :-)
  • Neophile
    Neophile over 12 years
    I'm sure this would work, but I am a bit new to working with reinterpret_cast and was not able to use this in my program. But really thanks for your answer.
  • Kerrek SB
    Kerrek SB over 12 years
    Isn't this making the dangerous and unchecked assumption that sizeof(float) does not exceed 4, and would otherwise trash your memory?
  • Kerrek SB
    Kerrek SB over 12 years
    @Nerds: Feel free to go with another answer, or to ask for more details, but be aware that you accepted an answer that's broken and dangerous.
  • Semjon Mössinger
    Semjon Mössinger about 8 years
    By looping from 0 to 3 you flip the result from left to right! Instead of "428CF6C9" you will get "C9F68C42".
  • Toby Speight
    Toby Speight almost 7 years
    This seems to assume that sizeof (float) is 4 - can you justify that?
  • Grim Fandango
    Grim Fandango almost 7 years
    @TobySpeight, I changed the code to cater for all cases of sizeof(float)