在 C++ 中浮点到二进制 [英] Float to binary in C++

查看:33
本文介绍了在 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.

这篇关于在 C++ 中浮点到二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆