简体   繁体   中英

C++ - Operating on the bits in a floating point value

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM