0

I am interacting with hardware that gives me various kinds of data packed away inside arrays of uint32_t. Unfortunately, I've forgotten how to interpret one of those as a 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)

What painfully obvious mistake am I making?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

2 Answers2

10

You are masking x with 0xffff, which is only 16 bits. You need to mask it with 0xffffffff for 32bits, otherwise you will lose bits.

Chris
  • 2,655
  • 2
  • 18
  • 22
  • 1
    Why not simply assign it directly? Surely it will truncate the top 32bits. – Puppy Mar 13 '14 at 22:05
  • @DeadMG You'd at least need a cast, both to silence compiler warnings and to show readers that the truncation is intended. But yes, it would probably be an easier (no counting F's) alternative. –  Mar 13 '14 at 22:06
  • Instead of merely describing the problem, you should demonstrate it with code, so that the OP can see it in context and try it out with copy/paste. – Cheers and hth. - Alf Mar 13 '14 at 22:11
  • 5
    @Cheersandhth.-Alf to be honest, the explanation is plenty clear and if the OP can't figure out how to amend his sample with this fix, then I wager he shouldn't be meddling with bit-level code in the first place... – sehe Mar 13 '14 at 22:12
-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;
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331