我不知道为什么包含OR返回错误的结果。
char arr[] = { 0x0a, 0xc0 };
uint16_t n{};
n = arr[0]; // I get 0x000a here.
n = n << 8; // Shift to the left and get 0x0a00 here.
n = n | arr[1]; // But now the n value is 0xffc0 instead of 0x0ac0.
这个例子中的错误是什么?控制台应用,MVS 社区 2017。
意外0xff
是由0xc0
的符号位扩展引起的。
0xc0 = 0b11000000
因此,设置了最上面的位,这意味着char
的符号(如signed char
)。
请注意,C++中的所有算术和按位运算至少可以使用int
(或unsigned int
)。较小的类型在之前升级,之后剪裁。
另请注意,char
可能是签名的,也可能是未签名的。这取决于编译器实现。显然,它是在OP的情况下签名的。为了防止意外的符号扩展,参数必须变得无符号(足够早)。
示范:
#include <iostream>
int main()
{
char arr[] = { 'x0a', 'xc0' };
uint16_t n{};
n = arr[0]; // I get 0x000a here.
n = n << 8; // Shift to the left and get 0x0a00 here.
n = n | arr[1]; // But now the n value is 0xffc0 instead of 0x0ac0.
std::cout << std::hex << "n (wrong): " << n << std::endl;
n = arr[0]; // I get 0x000a here.
n = n << 8; // Shift to the left and get 0x0a00 here.
n = n | (unsigned char)arr[1]; // (unsigned char) prevents sign extension
std::cout << std::hex << "n (right): " << n << std::endl;
return 0;
}
会期:
g++ -std=c++11 -O2 -Wall -pthread main.cpp && ./a.out
n (wrong): ffc0
n (right): ac0
科里鲁的生活演示
注意:
我必须改变char arr[] = { 0x0a, 0xc0 };
char arr[] = { 'x0a', 'xc0' };
解决严重的编译器投诉。我想,这些投诉与这个问题密切相关。
我通过执行以下操作使其正常工作:
int arr[] = { 0x0a, 0xc0 };
int n{};
n = arr[0]; // I get 0x000a here.
n = n << 8; // Shift to the left and get 0x0a00 here.
n = n | arr[1];
std::cout << n << std::endl;
如果您将"arr"数组保留为 char,则会有一些截断。
您已成为有符号整数提升的受害者。
将0xc0
分配给数组中的第二个元素(由于 MVS 而默认为有符号字符)时,表示如下:
arr[1] = 1100 - 0000, or in decimal -64
当它被强制转换为uint16_t
时,它被提升为值为-64
的整数。这是:
n = 1111 - 1111 - 1100 - 0000 = -64
由于整数的 2 补码实现。
因此:
n = 1111 - 1111 - 1100 - 0000
arr[1] = 0000 - 0000 - 1010 - 0000 (after being promoted)
n | arr[1] = 1111 - 1111 -1110-0000 = 0xffc0