Reading binary integers

c++, c++11

Solution

The commonly seen:

u = (int64_t)(((uint64_t)p[0] <<  0)
  + ((uint64_t)p[1] <<  8)
  + ((uint64_t)p[2] << 16)
  + ((uint64_t)p[3] << 24)
  + ((uint64_t)p[4] << 32)
  + ((uint64_t)p[5] << 40)
  + ((uint64_t)p[6] << 48)
  + ((uint64_t)p[7] << 56));

Is pretty much the only game in town for portability - it's otherwise tough to avoid potential alignment problems.

This answer does assume an 8-bit `char`. If you might need to support different sized `char`s, you'll need a preprocessor definition that checks CHAR_BIT and does the right thing for each.

Problem

``` const unsigned char* p; int64_t u = ...; // ?? ``` What's the recommended way to read a 64-bit binary little endian integer from the 8 bytes pointed to by p? On x64 a single machine instruction should do, but on big-endian hardware swaps are needed. How does one do this both optimally and portably? Carl's solution is good, portable enough but not optimal. This begs the question: why doesn't C/C++ provide a better and standardized way to do this? It's not an uncommon construct.

Original source