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

前端 未结 6 971
太阳男子
太阳男子 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: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 
    #include 
    
    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);
    }
    

提交回复
热议问题