序列化64位宽度整数

时间:2011-10-30 22:13:21

标签: c serialization

我有一个问题,我无法序列化64位整数(32位工作)

代码如下:

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);
然而,编译器警告我,对于高32位,我的位移太远了。 sizeof运算符告诉我它的64位宽度?

输出是:

uint64_t width: 8
uint64 value: 0x78563412

这是怎么回事?

3 个答案:

答案 0 :(得分:6)

你需要在移动前施放,例如

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

实际上你甚至不需要面具所以这可以简化为:

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

答案 1 :(得分:1)

0xFF00000000000000是一个int32常量。应0xFF00000000000000LLU改为

答案 2 :(得分:0)

编译器将buffer [i]转换为32位的int。 您需要显式地将缓冲区转换为64位无符号整数。 即

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

并将LLU添加到常量的末尾