如何用无符号long表示浮点值 [英] How to represent float value in unsigned long
问题描述
我正在开发C ++应用程序,以将一些浮点值写入EEPROM芯片.
我将此浮点数据转换为unsigned long,并从long中提取每个位,然后将32位写入内存.
一切正常,但是当我分配一个无符号的long值并从float读取时,它的并集发生变化.我得到 1.4013e-45 浮点值是正确的吗? 1
我的代码是
typedef 工会
{
float floatValue;
unsigned long longValue;
} LONG_FLOAT_UNION;
LONG_FLOAT_UNION lfu; lfu.longValue = 1; lfu.floatValue //This variable prints 1.4013e-45
我如何才能有效地将float转换为unsigned long和将unsigned long转换为float而不会丢失其十进制值.我不能乘以浮点值来表示无符号long.
我不确定您是否不理解并集或数字.浮点数和整数不同.浮点数以IEEE 754格式存储: https://msdn.microsoft.com/en-us/library /0b34tf65.aspx [ ^ ]
换句话说,即使长整数存储在内存中的内容与浮点存储的内容即使占用相同的字节数,也绝对没有关联.您的假设是错误的.
当将long int设置为1时,请设置与IEEE 754中的一个非常小的数字相对应的LSB.
在此处进行测试: http://www.h-schmidt.net/FloatConverter/IEEE754.html [ ^ ]
这样做可能更具有启发性:
lfu.floatValue = 1 .0f;
并查看long int值是什么.
如果您不能使用浮点数,则必须编写自己的代码来完成任务.
报价:是正确的,我得到了1.4013e-45浮点值为1的不可见值是的,这是正确的.您可以在此页面上尝试一下(以数字的十六进制或二进制表示形式插入
1
并查看结果).
现在,如果您准确说明您的要求,我们会更好地提供帮助.
I am developing a C++ application to write some float value to an EEPROM chip.
I am converting this float data to unsigned long and extracted each bit from long and write 32 bit to the memory.
Everything works fine, but when I assign an unsigned long value and read from float it changes in union. Is it correct I got 1.4013e-45 float value for unsgned 1
My code is
typedef union { float floatValue; unsigned long longValue; } LONG_FLOAT_UNION;
LONG_FLOAT_UNION lfu; lfu.longValue = 1; lfu.floatValue //This variable prints 1.4013e-45
How i can effectively convert float to unsigned long and unsigned long to float without losing its decimal values. I cant multiply with float values to represent in unsigned long.解决方案I am not sure whether you don''t understand unions or numbers. Floats and ints are different. A float is stored in IEEE 754 format: https://msdn.microsoft.com/en-us/library/0b34tf65.aspx[^]
To put this another way there is absolutely no correlation between what is stored in memory for a long int and what is stored for a float even if they occupy the same number of bytes. Your assumptions are false.
When you set the long int to 1 so setting the LSB that corresponds to a very small number in IEEE 754.
Test here: http://www.h-schmidt.net/FloatConverter/IEEE754.html[^]
It may be more illuminating to do this:
lfu.floatValue = 1.0f;
and see what the long int value is.
If you can''t use floats you will have to write your own code to do the task.
Quote:Is it correct I got 1.4013e-45 float value for unsgned 1
Yes it is correct. You may try yourself it at this page (insert
1
in the hexadecimal or binary representation of the number and see the result).
Now we could better help if you state exactly your requirements.
这篇关于如何用无符号long表示浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!