I would like to pack 2 floats into an long long. What would be the correct way to do this?
Slightly depends how portable you want it to be, in two senses: what platforms it works on at all, and what platforms it gives the same answer on. But something like this.
#include <stdint.h>
long long pack(float lo, float hi) {
assert(sizeof(float) == 4);
assert(sizeof(long long) == 8);
assert(CHAR_BIT == 8);
uint32_t target;
memcpy(&target, &lo, sizeof(target));
long long result = target;
memcpy(&target, &hi, sizeof(target));
result += ((long long)target) << 32;
return result;
}
The "other" way to get the bits of a float as an integer in one write+read is with a so-called "union cast", but I prefer memcpy. You can also access the float one unsigned char at a time and build up the long long with 8-bit shifts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With