美好的一天,我在16位C环境中工作,我想将浮点值转换为其位序列,如整数值.我知道如何实现这一目标有多种方式,一种是联盟; 如:
union ConvertFloatToInt
{
float input;
unsigned long output;
};
Run Code Online (Sandbox Code Playgroud)
这将通过读取相同的内存区域将浮动值"转换"为long值,只是以不同的方式解释它.
union ConvertFloatToInt x;
x.input = 20.00;
Run Code Online (Sandbox Code Playgroud)
结果
x.output = 0x41A00000;
Run Code Online (Sandbox Code Playgroud)
其他方法是void指针转换...
float input = 40.00;
unsigned long output;
void* ptr;
ptr = &input;
output = *(unsigned long*) ptr;
Run Code Online (Sandbox Code Playgroud)
结果
output = 0x42200000;
Run Code Online (Sandbox Code Playgroud)
这是我想要做的事情的想法,但是,我希望编译器在构建期间为我做转换,而不是在运行时.
我需要一个将转换后的浮动数据插入常量(const)unsigned long.
我正在考虑尝试将浮点值转换为void,然后将void转换为unsigned long.这样的事情:(是的,这是不正确的,你不能投无效)
const unsigned long FloatValue = (unsigned long) ((void) ((float) 20.654));
Run Code Online (Sandbox Code Playgroud)
有办法做到这一点吗?我想的可能是使用void指针的东西,但我知道的所有void指针都需要一个变量,并且变量可能不会用于const值的赋值.
编辑
我正在使用C90编译器.该问题适用于文件范围.
结论
结论是,除了在块范围内工作外,这个问题没有真正的解决方案.给出了多个答案,我感谢你们所有人.
我的解决方案
这不是一个好的解决方案,但它解决了我的问题,但我不认为这对许多人也有帮助.我创建了一个用于演示目的的小程序.这不是我的项目代码,也不是我的项目中使用的编译器(在有人说这不是C90编译器之前)
演示中使用的编译器:gcc(Ubuntu/Linaro 4.6.3-1ubuntu5)4.6.3
typedef union
{
float myfloat;
unsigned long mylong;
} custom_type;
typedef struct …Run Code Online (Sandbox Code Playgroud)