按位包含 OR 的错误结果
Wrong result with bitwise inclusive OR
我不知道为什么包含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
相关文章:
- 如何修复循环中的错误产生的错误结果?
- 添加可变参数函数的错误结果
- 使用特征 3 线性系统求解器的错误结果
- 按位包含 OR 的错误结果
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- STD :: FPCLASSIFY的错误结果使用Valgrind进行长时间的双重双重结果
- 视觉工作室的错误结果
- 将C#struct传递给C 不受管理的DLL返回错误结果
- 最长的常见子字错误结果
- 华氏度到摄氏度的错误结果
- UE4中简单坐标变换的错误结果
- 记忆错误结果的说明[编译器行为]
- 如何解决错误PRJ0002:错误结果 -1073741515从"cl.exe"返回?
- 错误 PRJ0002:错误结果 -1073741515 从"C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.
- glGetUniformLocation OpenGL ES 2.0(在ipad 3 iOS 7.0.3上返回错误结果)
- 在模板函数中调用std::for_each时出现错误结果
- 使用copy和back_inserter将矢量附加到其自身时出现错误结果
- CUDA 线程在全局内存中的私有位置写入时出现错误结果
- 来自 c++ 代码的错误结果
- 使用浮点值和铸造的算术运算的错误结果 - 差异很大,我想这不是准确值的情况(429497)?