Serialize a 64-bit integer

I have a problem when I cannot serialize a 64 bit integer (32 bit works)

The code is as follows:

uint64_t t = (uint64_t) 0; uint8_t buffer[8]; buffer[0] = 0x12; buffer[1] = 0x34; buffer[2] = 0x56; buffer[3] = 0x78; buffer[4] = 0x9A; buffer[5] = 0xBC; buffer[6] = 0xDE; buffer[7] = 0xF0; printf("uint64_t width: %lu\n",sizeof(t)); t |= (uint64_t) ( (buffer[7] << (7*8)) & 0xFF00000000000000 ); t |= (uint64_t) ( (buffer[6] << (6*8)) & 0x00FF000000000000 ); t |= (uint64_t) ( (buffer[5] << (5*8)) & 0x0000FF0000000000 ); t |= (uint64_t) ( (buffer[4] << (4*8)) & 0x000000FF00000000 ); t |= (uint64_t) ( (buffer[3] << (3*8)) & 0x00000000FF000000 ); t |= (uint64_t) ( (buffer[2] << (2*8)) & 0x0000000000FF0000 ); t |= (uint64_t) ( (buffer[1] << (1*8)) & 0x000000000000FF00 ); t |= (uint64_t) ( (buffer[0]) & 0x00000000000000FF ); printf("uint64 value: 0x%llu\n",t); 

however, the compiler warns me that my bit has been shifted too much for the upper 32 bits. The sizeof operator tells me its 64-bit width, though?

:

 uint64_t width: 8 uint64 value: 0x78563412 

What is going on here?

+4
source share
3 answers

You need to quit before the shift, for example

 t |= ((uint64_t)buffer[7] << (7*8)) & 0xFF00000000000000LLU; 

In fact, you don’t even need a mask, so this can simply be simplified:

 t |= (uint64_t)buffer[7] << (7*8); 
+6
source

0xFF00000000000000 is an int32 constant. Instead of 0xFF00000000000000LLU

+1
source

The compiler converts the buffer [i] to int, which is 32 bits. You need to explicitly use the buffer for the 64-bit unsigned int. i.e

 ((uint64_t)buffer[i]) << (numBitsToShift) 

and add LLU to the end of your constants

0
source

All Articles