How to store a 64 bit integer in two 32 bit integers and convert back again

I'm pretty sure its just a matter of some bitwise operations, I'm just not entirely sure of exactly what I should be doing, and all searches return back "64 bit vs 32 bit".


Solution 1:

pack:

u32 x, y;
u64 v = ((u64)x) << 32 | y;

unpack:

x = (u32)((v & 0xFFFFFFFF00000000LL) >> 32);
y = (u32)(v & 0xFFFFFFFFLL);

Solution 2:

Or this, if you're not interested in what the two 32-bits numbers mean:

u32 x[2];
u64 z;
memcpy(x,&z,sizeof(z));
memcpy(&z,x,sizeof(z));

Solution 3:

Use a union and get rid of the bit-operations:

<stdint.h> // for int32_t, int64_t

union {
  int64_t big;
  struct {
    int32_t x;
    int32_t y;
  };
};
assert(&y == &x + sizeof(x));

simple as that. big consists of both x and y.

Solution 4:

I don't know if this is any better than the union or memcpy solutions, but I had to unpack/pack signed 64bit integers and didn't really want to mask or shift anything, so I ended up simply treating the 64bit value as two 32bit values and assign them directly like so:

#include <stdio.h>
#include <stdint.h>

void repack(int64_t in)
{
    int32_t a, b;

    printf("input:    %016llx\n", (long long int) in);

    a = ((int32_t *) &in)[0];
    b = ((int32_t *) &in)[1];

    printf("unpacked: %08x %08x\n", b, a);

    ((int32_t *) &in)[0] = a;
    ((int32_t *) &in)[1] = b;

    printf("repacked: %016llx\n\n", (long long int) in);
}

Solution 5:

The basic method is as follows:

uint64_t int64;
uint32_t int32_1, int32_2;

int32_1 = int64 & 0xFFFFFFFF;
int32_2 = (int64 & (0xFFFFFFFF << 32) ) >> 32;

// ...

int64 = int32_1 | (int32_2 << 32);

Note that your integers must be unsigned; or the operations are undefined.