I won't ask how you ended up with a big-endian, six-byte buffer.
const int odd_buffer_size = 6;
char src[ odd_buffer_size ] = { … };
uint64_t dst = 0;
// Copy the big-endian data into a big-endian long:
memcpy( ( (char*) & dst ) + 2, src, odd_buffer_size );
// Read the data as a value (aliasing-safe) and convert endianness:
dst = ntohll( dst );
ntohll
is not standard C, but is available in Windows and sometimes on Linux. Names for it seem to vary across platforms (e.g. be64toh
), but some facility is always available.
By the way, the trick uint32_t val = *(uint32_t*) buf;
is unsafe because the buffer may be (in this particular case, almost certainly is) improperly aligned for accessing a uint32_t
value.
Even forming a value of type uint32_t *
with an odd address is enough to potentially crash in C. Always use memcpy
or a union
when reinterpreting bytes.