Click here to Skip to main content
15,889,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C++
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.
Posted
Updated 27-Jul-15 19:48pm
v2
Comments
Michael_Davies 28-Jul-15 2:22am    
You need to understand how a float is mapped in memory, it is not as straight forward as a non-decimal number such as a long.

For a nice picture look at : http://stackoverflow.com/questions/6910115/how-to-represent-float-number-in-memory-in-c

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:
C++
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.
 
Share this answer
 
v5
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900