C ++将整数复制到char []或unsigned char []错误

问题描述 投票:0回答:3

所以我使用以下代码将一个整数放入char []或unsigned char []

(unsigned???) char test[12];

test[0] = (i >> 24) & 0xFF;
test[1] = (i >> 16) & 0xFF;
test[2] = (i >> 8) & 0xFF;
test[3] = (i >> 0) & 0xFF;

int j = test[3] + (test[2] << 8) + (test[1] << 16) + (test[0] << 24);

printf("Its value is...... %d", j);

当我使用类型unsigned char和值1000000000时,它正确打印。

当我使用char类型(相同的值)时,我打印98315724?

所以,问题真的是任何人都可以解释到底是怎么回事?


在检查两个不同数字的二进制文件后,我仍然无法解决最新情况。我认为签名是在MSB设置为1时表示负值(但是负值??)?

我明确地告诉缓冲区要插入什么,以及如何解释内容,所以不明白为什么会发生这种情况。

为了清楚起见,我在下面列出了二进制/十六进制。

11 1010 1001 1001 1100 1010 0000 0000 //二进制983157248

11 1011 1001 1010 1100 1010 0000 0000 //二进制为1000000000

3 A 9 9 C A 0 0 // 983157248的十六进制

3 B 9 A C A 0 0 //十六进制为1000000000

c++ arrays integer char unsigned
3个回答
0
投票

除了Kerrek SB的答案外,请考虑以下事项:

计算机(几乎总是)使用称为twos-complement notation的东西作为负数,高位作为“负”指标。问问自己,当您在签名类型上执行轮班时会发生什么,考虑到计算机将专门处理已签名的位。

您可能想在StackOverflow上阅读Why does left shift operation invoke Undefined Behaviour when the left side operand has negative value?以获取提示。


0
投票

当你说i & 0xFF等时,你就是在[0, 256)范围内创造价值。但是(你的)char有一系列的[-128, +128),因此你无法合理地存储这些值(即行为是实现定义的,而且很难推理)。

使用unsigned char表示无符号值。线索就在名字中。


0
投票

这一切都与internal representation和每个type使用data解释它的方式有关。在internal representationsigned character中,你的字节的第一位保持符号,其他的是值。当第一位为1时,数字为负,后面的位表示正值的complement。例如:

unsigned char c;  // whose internal representation we will set at 1100 1011
c = (1 * 2^8) + (1 * 2^7) + (1 * 2^4) + (1 * 2^2) + (1 * 2^1);
cout << c;        // will give 203

                  // inversely:

char d = c;       // not unsigned
cout << d;        // will print -53
                  // as if the first is 1, d is negative, 
                  // and other bits complement of value its positive value
                  // 1100 1011  -> -(complement of 100 1011)
                  // the complement is an XOR +1   011 0101

                  // furthermore:

char e;           // whose internal representation we will set at 011 0101
e = (1 * 2^6) + (1 * 2^5) + (1 * 3^2) + (1 * 2^1);
cout << e;        // will print 53
© www.soinside.com 2019 - 2024. All rights reserved.