如何将float转换或转换为其位序列,例如long

use*_*047 5 c floating-point casting

美好的一天,我在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
{
            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;
}
Run Code Online (Sandbox Code Playgroud)

产量

:: 3.840000
:: 1081459343l
Run Code Online (Sandbox Code Playgroud)

这有点粗糙,但它适用于文件范围(但会生成警告).

eca*_*mur 5

你可以通过匿名联合打字来做到这一点:

unsigned int i = ((union { float f; unsigned int i; }){5.0}).i;
Run Code Online (Sandbox Code Playgroud)

请注意,此初始化程序不是常量表达式,因此不能在文件范围内使用.

脚注中的标准允许通过联合进行类型标记:

6.5.2.3结构和工会成员

95)如果用于读取union对象内容的成员与上次用于在对象中存储值的成员不同,则该值的对象表示的适当部分将被重新解释为新对象表示如6.2.6所述的类型(有时称为''punning''的过程).这可能是陷阱表示.

从实际的角度来看,虽然您不能使用此方法初始化文件范围常量,但您可以编写初始化函数,在程序或模块初始化时将值加载到文件范围变量中.

您不会找到允许您将值计算为编译时常量表达式的可移植方法,因为标准6.2.6部分所涵盖的对象表示仅适用于运行时.否则,需要交叉编译器来模拟而不仅仅是参数化其目标的执行环境.


附录:这有效的C++,条件是union必须命名类型:

union u { float f; unsigned int i; };
unsigned int i = u{5.0}.i;
Run Code Online (Sandbox Code Playgroud)

因此,如果您愿意使用混合C/C++编写并使用C++编译器进行编译,那么您可以在编译时执行转换.