获取IEEE单precision位的浮点 [英] Getting the IEEE Single-precision bits for a float
问题描述
我需要写一个IEEE单precision浮点数为32位硬件寄存器在一个特定的地址。要做到这一点,我需要一个float类型的变量转换为一个无符号整数。我可以再presentation这样的整数:
I need to write an IEEE single-precision floating point number to a 32-bit hardware register at a particular address. To do that, I need to convert a variable of type float to an unsigned integer. I can get the integer representation like this:
float a = 2.39;
unsigned int *target;
printf("a = %f\n",a);
target = &a;
printf("target = %08X\n",*target);
返回:
a = 2.390000
target = 4018F5C3
都很好。然而,这会导致编译器警告cast.c:12:警告:从兼容的指针类型赋值
All good. However this causes a compiler warning "cast.c:12: warning: assignment from incompatible pointer type"
有没有其他办法做到这一点不产生警告?这是一个特定的硬件,我并不需要处理不同的字节顺序等,我不通过每个字符出于性能的考虑要循环其他一些问题,往往建议。好像你也许能够使用reinter pret_cast在C ++中,但我使用C
Is there any other way to do this which doesn't generate the warning? This is for specific hardware, I don't need to handle different endianness etc and I don't want to loop through each char for performance reasons as some other questions tend to suggest. It seems like you might be able to use reinterpret_cast in C++ but I am using C.
推荐答案
您可以使用双关语的类型与工会,
You can use type punning with a union,
union {
float f;
uint32_t u;
} un;
un.f = your_float;
uint32_t target = un.u;
得到位。或者你可以使用的memcpy
。
这篇关于获取IEEE单precision位的浮点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!