我正在尝试将整数值复制到 char *,但对于大于 127 的整数我总是得到奇怪的结果。
int main(int argc, char **argv) {
printf("Running test\n");
char x[2];
int y = 127, z = 128;
printf("\ny: "); fflush(stdout);
for (int i = 0; i < 32; i++) {
printf("%d", (y >> i) & 0x1);
fflush(stdout);
}
printf("\nz: "); fflush(stdout);
for (int i = 0; i < 32; i++) {
printf("%d", (z >> i) & 0x1);
fflush(stdout);
}
*x = y;
printf("\nxy: "); fflush(stdout);
for (int i = 0; i < 32; i++) {
printf("%d", (*x >> i) & 0x1);
fflush(stdout);
}
printf("\nxz: "); fflush(stdout);
*x = z;
for (int i = 0; i < 32; i++) {
printf("%d", (*x >> i) & 0x1);
fflush(stdout);
}
return 0;
}
结果:
<小时/>运行测试
y:11111110000000000000000000000000
z: 00000001000000000000000000000000
xy: 11111110000000000000000000000000
xz: 00000001111111111111111111111111
对于编译,我使用 gcc v 5.4.0(如果重要的话,仅使用输出标志): “gcc test.c -o 测试”
感谢任何帮助
最佳答案
如果您有一个signed char
,它通常可以表示 -128 到 +127 范围内的数字。大多数编译器默认使用带符号的 char
。
因此,即使不进行移位,127 以上的数字也无法正确表示。
此外,右移负符号值也是实现定义的。
关于c - 在 c 中将整数复制到 char * 时出现奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42417935/