2

I have a string containing, for example "3F800000".

This is a hexadecimal representation of the float 1.0 Only I can't seem to find any convenient way of making this conversion in C++. Suggestions?

Unreasonable
  • 23
  • 1
  • 4

1 Answers1

5

Assuming 32-bit int and float,

unsigned int x;
std::stringstream ss;
ss << std::hex << "3F800000";
ss >> x;
return reinterpret_cast<float&>(x);
ephemient
  • 189,938
  • 36
  • 271
  • 385
  • 2
    @ardiyu07: "3F800000" is the binary representation "1.0" in IEEE-754's `binary32`. What the heck does "3F800000.24" mean? – ephemient Feb 17 '11 at 17:04
  • This works, but it breaks strict aliasing: http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule – Fred Larson Feb 17 '11 at 17:29
  • @ephemient C99 allows floating point hex, it allows a double to be represented without losing information (it came as a surprise to me aswell) – Martin Beckett Feb 17 '11 at 18:13
  • 1
    @Martin @ardiyu07: Floating-point hex is quite different from the bit-wise layout of IEEE 754. For example, "1.0" would simply be "0x1.0". – ephemient Feb 17 '11 at 18:15
  • @ephemient - true, I was just pointing out that "3F800000.24" is valid in C99, of course it has no similarity with the contents of a double in memory – Martin Beckett Feb 17 '11 at 18:58
  • @Martin: 3F800000.24 isn't a valid hex floating literal. 0x3F800000.24, on the other hand, is. – ephemient Feb 17 '11 at 19:32
  • @ephemient - doing embedded wire protocol stuff at the moment. So I'm seeing 0x in front of my eyes! – Martin Beckett Feb 17 '11 at 23:14