Problem:
I would like to pass all the content of a float32 variable to a int32 however doing the following:
float32 source;
int32 destination;
source = 23.59463; // Hex = 0x41BCC1CE
destination = 0; // Hex = 0x00000000
destination = source; // Destination = 0x00000017 = 23
This does not pass all the content. I have tried casting, and tried to get the content indirectly but then I get issues with pointer types.
Question:
1) How can I grab all the content of the float32 into the int32?
If you want a byte-by-byte copy, that's
assert(sizeof(source) == sizeof(destination));
memcpy(&destination, &source, sizeof(source));
As an alternative answer, there's always fun with pointers:
destination = *(int32*)&source;
When you do the assignment destination = source
the source
variable is casted to an integer, and thereby truncated.
One way of overcoming this problem is to use a union
:
union U
{
float32 f;
int32 i;
};
union U u;
u.f = 23.59463;
printf("%08x\n", u.i);
Note: If you intend to send this integer (over network or serial communication) then you have to remember that different platform have different endianness.
If "all the content" means all the digits, you can multiply source to get fixed point destination.
destination = source * 100000;//23.59463 * 100000 = 2359463
User contributions licensed under CC BY-SA 3.0