gpt4 book ai didi

c - 序列化 64 位宽度整数

转载 作者:太空狗 更新时间:2023-10-29 15:24:56 25 4
gpt4 key购买 nike

我遇到无法序列化 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

这是怎么回事?

最佳答案

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

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

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

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

关于c - 序列化 64 位宽度整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7948260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com