Float to binary in C++(在 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++ 中浮点到二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中浮点到二进制
				
        
 
            
        基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				