gpt4 book ai didi

将字节数组转换为 int

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

我有一个包含四个 bytes 的数组,我想将其转换为 int。以下代码适用于此:

#include <stdio.h>
#include <stdint.h>

int main(void) {
uint8_t array[4] = {0xDE, 0xAD, 0xC0, 0xDE};
uint32_t myint;
myint = (uint32_t)(array[0]) << 24;
myint |= (uint32_t)(array[1]) << 16;
myint |= (uint32_t)(array[2]) << 8;
myint |= (uint32_t)(array[3]);

printf("0x%x\n",myint);
return 0;
}

结果符合预期:

$./test
0xdeadc0de

现在我想像这样在一行中执行此操作:

#include <stdio.h>
#include <stdint.h>

int main(void) {
uint8_t array[4] = {0xDE, 0xAD, 0xC0, 0xDE};
uint32_t myint = (uint32_t)(array[0]) << 24 || (uint32_t)(array[1]) << 16 || (uint32_t)(array[2]) << 8 || (uint32_t)(array[3]);

printf("0x%x\n",myint);
return 0;
}

但这会导致:

$./test
0x1

为什么我的程序会这样?

最佳答案

您混淆了逻辑(||)和位(|).

uint32_t myint = (uint32_t)(array[0]) << 24 
| (uint32_t)(array[1]) << 16
| (uint32_t)(array[2]) << 8
| (uint32_t)(array[3]);

关于将字节数组转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33822550/

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