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

Floating Point to Binary Value(C++)(浮点到二进制值(C++))
本文介绍了浮点到二进制值(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

这篇关于浮点到二进制值(C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)