在 C++ 中浮点到二进制

2022-01-17 00:00:00 floating-point numbers c++

我想知道是否有办法在 C++ 中使用 char 来表示浮点数?

I'm wondering if there is a way to represent a float using a char in C++?

例如:

int main()  
{  
    float test = 4.7567;  
    char result = charRepresentation(test);  
    return 0;  
}  

我读到可能使用 bitset 我可以做到,但我不太确定.

I read that probably using bitset I can do it but I'm not pretty sure.

假设我的浮点变量是二进制的 01001010 01001010 01001010 01001010.

Let's suppose that my float variable is 01001010 01001010 01001010 01001010 in binary.

如果我想要一个 4 个元素的 char 数组,第一个元素是 01001010,第二个元素是 01001010,依此类推.

If I want a char array of 4 elements, the first element will be 01001010, the second: 01001010 and so on.

我可以在 4 个元素的 char 数组中表示浮点变量吗?

Can I represent the float variable in a char array of 4 elements?

推荐答案

我怀疑你想说的是:

int main()  
{  
    float test = 4.7567; 
    char result[sizeof(float)];

    memcpy(result, &test, sizeof(test));

    /* now result is storing the float,
           but you can treat it as an array of 
           arbitrary chars

       for example:
    */
    for (int n = 0; n < sizeof(float); ++n) 
        printf("%x", result[n]);

    return 0;  
}  

编辑添加:所有指出你不能将 float 放入 8 位的人当然是正确的,但实际上 OP 正在摸索理解 float 和所有原子数据类型一样,最终是一个简单的连续字节块.这对所有新手来说都不是显而易见的.

Edited to add: all the people pointing out that you can't fit a float into 8 bits are of course correct, but actually the OP is groping towards the understanding that a float, like all atomic datatypes, is ultimately a simple contiguous block of bytes. This is not obvious to all novices.

相关文章