Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing Floats into a long long

I would like to pack 2 floats into an long long. What would be the correct way to do this?

like image 380
Hamza Yerlikaya Avatar asked Jan 27 '26 02:01

Hamza Yerlikaya


1 Answers

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.

like image 177
Steve Jessop Avatar answered Jan 28 '26 15:01

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!