简体   繁体   English

C ++-对浮点值中的位进行运算

[英]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 . 我正在尝试编写一个将一组字节重新解释为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. 我已经看过一个Stackoverflow问题 ,这使我尝试对字符数组进行reinterpret_cast<>()的工作,然后我开始尝试将一个float拆分为char,然后再次对其进行重新组装,但这只是给我看似随机数而不是我的数字认为值应该是,因为每次输出都不同。 A few different examples are: 一些不同的示例是:

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

The float variable should contain the value 5.2. float变量包含值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. 所以我的问题是-如何将float类型的变量(以后是double )拆分为单个字节(允许我修改位),然后重新组装它。

Any help would be greatly appreciated. 任何帮助将不胜感激。

bytes is a pointer . bytes是一个指针

Change 更改

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

to

float f1 = *reinterpret_cast<float*>(bytes);
// Cast to a different pointer... ^
//         ^ ...and dereference that pointer.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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