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

前端 未结 6 938
太阳男子
太阳男子 2020-11-30 02:09

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

相关标签:
6条回答
  • 2020-11-30 02:20

    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));
    
    0 讨论(0)
  • 2020-11-30 02:25

    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.

    0 讨论(0)
  • 2020-11-30 02:28
    long x = 0xFEDCBA9876543210;
    cout << hex << "0x" << x << endl;
    
    int a = x ; 
    cout << hex << "0x" << a << endl;
    int b = (x >> 32);
    cout << hex << "0x" << b << endl;
    
    0 讨论(0)
  • 2020-11-30 02:34

    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.

    0 讨论(0)
  • 2020-11-30 02:35

    pack:

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

    unpack:

    x = (u32)((v & 0xFFFFFFFF00000000LL) >> 32);
    y = (u32)(v & 0xFFFFFFFFLL);
    
    0 讨论(0)
  • 2020-11-30 02:38

    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);
    }
    
    0 讨论(0)
提交回复
热议问题