Question

My machine is 64 bit. My code as below:

unsigned long long periodpackcount=*(mBuffer+offset)<<32|*(mBuffer+offset+1)<<24|*     (mBuffer+offset+2)<<16|*(mBuffer+offset+3)<<8|*(mBuffer+offset+4);

mBuffer is unsigned char*. I want to get 5 bytes data and transform the data to host byte-order. How can I avoid this warning ?

Was it helpful?

Solution

Sometimes it's best to break apart into a few lines in order to avoid issues. You have a 5 byte integer you want to read.

// Create the number to read into.
uint64_t number = 0;  // uint64_t is in <stdint>
char *ptr = (char *)&number;

// Copy from the buffer. Plus 3 for leading 0 bits.
memcpy(ptr + 3, mBuffer + offset, 5);

// Reverse the byte order.
std::reverse(ptr, ptr + 8);  // Can bit shift here instead

Probably not the best byte swap ever (bit shifting is faster). And my logic might be off for the offsetting, but something along those lines should work.

The other thing you may want to do is cast each byte before shifting since you're leaving it up to the compiler to determine the data type *(mBuffer + offset) is a character (I believe), so you may want to cast it to a larger type static_cast<uint64_t>(*(mBuffer + offset)) << 32 or something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top