浮点到二进制值(C++)

2022-01-09 00:00:00 floating-point binary ieee-754 c++

我想在 C++ 中获取一个浮点数,例如 2.25125,以及一个填充了二进制值的 int 数组,该二进制值用于将浮点数存储在内存中 (IEEE 754).

I want to take a floating point number in C++, like 2.25125, and a int array filled with the binary value that is used to store the float in memory (IEEE 754).

所以我可以取一个数字,最后得到一个带有浮点二进制值的 int num[16] 数组:num[0] 将是 1num[1] 将是 1num[2] 将是 0num[3] 将是 1等等……

So I could take a number, and end up with a int num[16] array with the binary value of the float: num[0] would be 1 num[1] would be 1 num[2] would be 0 num[3] would be 1 and so on...

将 int 放入数组并不难,只是获取浮点数的二进制值的过程是我遇到的问题.您可以只读取浮点变量的内存中的二进制文件吗?如果没有,我怎么能在 C++ 中做到这一点?

Putting an int into an array isn't difficult, just the process of getting the binary value of a float is where I'm stuck. Can you just read the binary in the memory that the float variable? If not, how could I go about doing this in C++?

以这种方式进行比较的原因是我想学习在 C++ 中进行按位运算.

The reason for doing the comparison this way is that I am wanting to learn to do bitwise operations in C++.

推荐答案

使用 union 和 bitset:

Use union and bitset:

#include <iostream>
#include <bitset>
#include <climits>

int main()
{
    union
    {
        float input; // assumes sizeof(float) == sizeof(int)
        int   output;
    } data;

    data.input = 2.25125;

    std::bitset<sizeof(float) * CHAR_BIT> bits(data.output);
    std::cout << bits << std::endl;

    // or
    std::cout << "BIT 4: " << bits[4] << std::endl;
    std::cout << "BIT 7: " << bits[7] << std::endl;
}

它可能不是数组,但您可以使用 [] 运算符访问位,就像使用数组一样.

It may not be an array but you can access bits with [] operator as if you were using an array.

输出

$ ./bits
01000000000100000001010001111011
BIT 4: 1
BIT 7: 0

相关文章