1

I'm trying to write a function that will reinterpret a set of bytes as a float. I have viewed a Stackoverflow question which lead me to try reinterpret_cast<>() on an array of characters, and I started experimenting with splitting a float into chars and then reassembling it again, but that only gives me seemingly random numbers rather than what I think the value should be, as the output is different each time. A few different examples are:

1.58661e-038
3.63242e-038
2.53418e-038

The float variable should contain the value 5.2.

Compiling the code:

float f = 5.2;
unsigned char* bytes = reinterpret_cast<unsigned char*>(&f);
float f1 = reinterpret_cast<float&>(bytes);

std::cout << f1 << std::endl;

gave me

1.75384e-038

And then of course, a different number each time the program is run. Interestingly, however, if I put the code in a loop and execute it several times in a single run, the output stays consistent. This leads me to think it might be a memory location, but if so, I'm not sure how to access the real value of the variable - the dereference operator doesn't work, because it's not a pointer.

So my question is - How can I split a variable of type float (and later on, a double) into individual bytes (allowing me to modify the bits), and then reassemble it.

Any help would be greatly appreciated.

Community
  • 1
  • 1
brads3290
  • 1,926
  • 1
  • 14
  • 20
  • 4
    You're close, but you should cast back to a `float*`, then dereference that. (Note that you are playing dangerously close to Undefined Behaviour here. Please don't do this in any production code.) – BoBTFish Apr 08 '15 at 15:49
  • Thanks :) Would you be able to elaborate on *Undefined Behaviour*? I'm not sure I understand what you mean. – brads3290 Apr 08 '15 at 15:51
  • 1
    @BradSullivan http://en.wikipedia.org/wiki/Undefined_behavior – Drew Dormann Apr 08 '15 at 15:52
  • 1
    @BradSullivan When you break the rules in languages like C++ or C, they don't hold your hand. They just make your program meaningless, and anything could happen (crash, appear to work, melt the walls, ...). You are strictly ok here, but very close to doing something illegal, for instance changing anything through `bytes`. – BoBTFish Apr 08 '15 at 15:54
  • Cheers. I didn't realise it was a coined term. Probably should have noted the capitalisation :) – brads3290 Apr 08 '15 at 15:56

1 Answers1

6

bytes is a pointer.

Change

float f1 = reinterpret_cast<float&>(bytes);

to

float f1 = *reinterpret_cast<float*>(bytes);
// Cast to a different pointer... ^
//         ^ ...and dereference that pointer.
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180