jeffreyveon
jeffreyveon

Reputation: 13830

Packing multiple integers into a 64 bit integer

I want to pack the following numbers into a 64 bit int64_t field in the following order:

So, the 64 bits should be in the following layout:

[  num1(8)  |  num2(8)  |       num3(32)       |   num4(16)  ]

I'm not able to wrap my head around the bit packing logic, i.e. I want those numbers to be packed into a single int64_t field, similar to this question.

Any help is greatly appreciated.

Upvotes: 0

Views: 2206

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50831

You probably want this:

  int8_t num1;
  int8_t num2;
  int32_t num3;
  int16_t num4;
  ...
  uint64_t number = ((uint64_t)num1 << (16 + 32 + 8)) | ((uint64_t)num2 << (16 + 32)) | ((uint64_t)num3 << 16) | (uint64_t)num4;

From this you should be able to figure out how to do the inverse conversion. If not, post another question.

Upvotes: 4

Related Questions