再会,
我在 16 位 C 环境中工作,我想将浮点值转换为其位序列,例如整数值。
我知道有多种方法可以实现这一目标,一种是通过工会;另一种是通过工会。例如:
union ConvertFloatToInt
{
float input;
unsigned long output;
};
这将通过读取相同的内存区域,将浮点值“转换”为长值,只是以不同的方式解释它。
union ConvertFloatToInt x;
x.input = 20.00;
result
x.output = 0x41A00000;
其他方法是 void 指针强制转换...
float input = 40.00;
unsigned long output;
void* ptr;
ptr = &input;
output = *(unsigned long*) ptr;
result
output = 0x42200000;
这是我想要做的想法,但是,我希望编译器在构建期间而不是运行时为我进行转换。
我需要将转换后的浮点数据插入到常量(const)无符号长整型中。
我正在考虑尝试将 float 值转换为 void,然后将 void 转换为 unsigned long。
像这样的东西:(是的,这是不正确的,你不能将其转换为空)
const unsigned long FloatValue = (unsigned long) ((void) ((float) 20.654));
有什么方法可以做到这一点吗?我在想也许有 void 指针,但我知道的所有 void 指针都需要一个变量,并且变量可能不能在 const 值的赋值中使用。
Edit
我使用的是 C90 编译器。
该问题是在文件范围内提出的。
结论
结论是,除了在块作用域中工作之外,这个问题没有真正的解决方案。对此大家给出了多个答案,我感谢大家。
我的解决方案
这不是一个好的解决方案,但是它解决了我的问题,但我认为这也不会帮助很多人。
我创建了一个小程序用于演示目的。这不是我的项目代码,也不是我的项目中使用的编译器(之前有人说这不是 C90 编译器)
演示使用的编译器:gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
typedef union
{
float myfloat;
unsigned long mylong;
} custom_type;
typedef struct
{
int a;
int b;
custom_type typeA;
custom_type typeB;
} my_struct;
const my_struct myobj =
{
1,2,3.84F,4
};
int main(void)
{
printf(":: %f\n", myobj.typeA.myfloat);
printf(":: %ul\n", myobj.typeA.mylong);
return 0;
}
Output
:: 3.840000
:: 1081459343l
这有点粗糙,但是它在文件范围内有效(但会生成警告)。