【发布时间】:2016-10-04 02:47:41
【问题描述】:
看看这段代码:
#include <stdio.h>
#include <stdlib.h>
int byteToInt(char *bytes) {
int32_t v =
(bytes[0] ) +
(bytes[1] << 8 ) +
(bytes[2] << 16) +
(bytes[3] << 24);
return v;
}
int main() {
char b1[] = {0xec, 0x51, 0x04, 0x00};
char b2[] = {0x0c, 0x0c, 0x00, 0x00};
printf("%d\n", byteToInt(b1));
printf("%d\n", byteToInt(b2));
printf("%d\n", *(uint32_t *)b1);
printf("%d\n", *(uint32_t *)b2);
return 0;
}
{0xec, 0x51, 0x04, 0x00} 等于283116,但是当我使用byteToInt 函数时,由于某种原因,它返回282860。有一些字节数组会引起类似的麻烦。我意识到这个值总是被 256 弄错。不过,大多数情况下都没有任何问题 - 看看b2,它被计算为3084,这是正确的。铸造方法在这些情况下非常有效,但我想知道所描述的问题发生了什么。有人可以向我解释一下吗?
【问题讨论】:
-
将
char数组转换为uint32_t *是未定义的行为,因为它违反了strict aliasing。这是在具有严格对齐要求的机器上获得SIGBUS的好方法。