我该如何打包和解压缩这个64位整数?

时间:2014-03-13 21:59:34

标签: c++

我正在与硬件进行交互,这些硬件为我提供了在uint32_t数组中打包的各种数据。不幸的是,我忘记了如何将其中一个解释为uint64_t

#include <iostream>
#include <cstdint>

int main()
{
   const uint64_t x = 123456789123456789ULL;

   // Pack into uint32_t[2]
   uint32_t ar[2] = {};
   ar[0] = x >> 32;
   ar[1] = x & 0xFFFF;

   // Unpack into uint64_t
   uint64_t y;
   y = ar[0];
   y = (y << 32) + ar[1];

   // The output should be the same!
   std::cout << x << ' ' << y << std::endl;
}

// Output: 123456789123456789 123456786224144149

live demo

我犯了什么痛苦的明显错误?

2 个答案:

答案 0 :(得分:10)

您正在使用0xffff屏蔽x,这只是16位。你需要用0xffffffff为32位屏蔽它,否则你会丢失位。

答案 1 :(得分:-2)

#include <iostream>
#include <cstdint>

int main()
{
   const uint64_t x = 123456789123456789ULL;

   // Pack into uint32_t[2]
   uint32_t ar[2] = {};
   ar[0] = x >> 32;
   ar[1] = x & 0xFFFFFFFF;

   // Unpack into uint64_t
   uint64_t y;
   y = ar[0];
   y = (y << 32) + (ar[1] & 0xFFFFFFFF);

   // The output should be the same!
   std::cout << x << ' ' << y << std::endl;
}