8
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.

11
  • 1
    int64_t is standard C++11. It does assume the type is available though.
    – XTF
    Feb 21, 2013 at 17:54
  • 1
    @XTF Exactly, that's what I mean. If the type is optionally available, then it's not portable. It's only portable among those systems that have a 64 bit type. Feb 21, 2013 at 17:57
  • 2
    Couldn't he just do int64_t u = *(int64_t *) p; u = le64toh(u); ??
    – Bill Lynch
    Feb 21, 2013 at 17:58
  • 2
    @sharth Simply put, no.
    – user529758
    Feb 21, 2013 at 18:01
  • 2
    @sharth No, it simply misses the point. The point is portability and avoiding UB arising out of alignment mismatch. What you suggest disregards the endianness of the target machine and also introduces a potential misalignment error.
    – user529758
    Feb 21, 2013 at 18:04

3 Answers 3

7

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 chars, you'll need a preprocessor definition that checks CHAR_BIT and does the right thing for each.

11
  • With my loop, a multiplication by CHAR_BIT does the trick, I believe :)
    – user529758
    Feb 21, 2013 at 17:57
  • @H2CO3, yeah that will work - but the compiler is under no requirement to optimize/unroll that loop. It'll probably work with most compilers, though.
    – Carl Norum
    Feb 21, 2013 at 17:59
  • @CarlNorum Eh, splitting hair... I'm not in the false belief that the compiler will unroll it, of course.
    – user529758
    Feb 21, 2013 at 18:00
  • Oops -- my apologies -- I missed the statement that the data was little-endian. Feb 21, 2013 at 18:00
  • @JerryCoffin No worries. Same thing happened to me today.
    – user529758
    Feb 21, 2013 at 18:01
4

Carl Norum is right - if you want to be readable as well, you can write a loop (the compiler will unroll it anyway). This will also nicely deal with non-8-bit chars.

u = 0;
const int n = 64 / CHAR_BIT + !!(64 % CHAR_BIT);
for (int i = 0; i < n; i++) {
    u += (uint64_t)p[i] << (i * CHAR_BIT);
}
8
  • Shouldn't it only loop 4 times if CHAR_BIT = 16?
    – XTF
    Feb 21, 2013 at 18:09
  • @XTF This will loop only 4 times if CHAR_BIT == 16, since 64 / 16 + !!(64 % 16) = 4 + !!0 = 4 + 0 = 4.
    – user529758
    Feb 21, 2013 at 18:10
  • If CHAR_BIT is 9 (parity bit), then your reads will either fall short or read too far. Feb 21, 2013 at 18:53
  • @MatthieuM. Why? It will then read 8 bytes (72 bits). What's the problem with that? If there's truly a 64-bit integer in the original data, the 8 most significant bits should be zero in the original representation, I assume.
    – user529758
    Feb 21, 2013 at 18:56
  • @H2CO3: you are making an assumption here, that 72 bits will have been written to the source you are reading from. This is only true if the source also used 9 bits a byte. Since the assumption is that the source may have a different byte order than the current process, why should it have the same CHAR_BIT ? And if it does not, then there may only have been 64 bits written where you are trying to read 72. Or am I wrong ? Feb 22, 2013 at 8:24
0

I used the following code to reverse the byte order for any variable. I used it to convert between different "Endianess".

// Reverses the order of bytes in the specified data
void ReverseBytes(LPBYTE pData, int nSize)
{
    int i, j;

    for (i = 0, j = nSize - 1; i < j; i++, j--)
    {
        BYTE nTemp = pData[i];
        pData[i] = pData[j];
        pData[j] = nTemp;
    }
}
6
  • 2
    That's bad, you shouldn't modify your input.
    – XTF
    Feb 21, 2013 at 18:03
  • 4
    No, it's not bad. Why would you suggest such an arbitrary rule? I've been doing this an awfully long time. It depends entirely on your needs. Feb 21, 2013 at 18:04
  • The rule is not arbitrary. ReverseBytes is not itself the problem; the caller of such a routine likely expects the data pointed to to be reversed. The problem is that if one uses ReverseBytes in a routine to convert little-endian data to a native integer, the caller of that routine likely does not expect the input data to be changed. So you are doing something unexpected that can cause a bug. Feb 21, 2013 at 20:23
  • Are you guys serious? I'm showing how to do what the OP asked about. I am not new to this. I'm using this in a real-world application and I have never had a problem such as being described. And if you think it could be a problem for your particular application, then modify it to make a copy for heaven's sake. I find the objection to be trivial, and incorrect when stated as an absolute. Feb 21, 2013 at 20:25
  • 3
    @XTF: "That's bad, you shouldn't modify your input": says who? the standard libs do it, too. Sometimes, it's what is needed, even though often, it is not. It depends. Feb 22, 2013 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.