我有一个简单的程序.请注意,我使用的是无符号的固定宽度整数1字节.
#include <cstdint>
#include <iostream>
#include <limits>
int main()
{
uint8_t x = 12;
std::cout << (x << 1) << '\n';
std::cout << ~x;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的输出如下.
24
-13
Run Code Online (Sandbox Code Playgroud)
我测试了更大的数字,操作员<<总是给我正数,而操作员~总是给我负数.我然后使用sizeof()并发现......
当我使用左移位运算符(
<<)时,我收到一个无符号的4字节整数.当我使用bitwise not运算符(
~)时,我收到一个带符号的4字节整数.
似乎bitwise not运算符(~)像算术运算符一样执行有符号整数提升.但是,左移运算符(<<)似乎提升为无符号整数.
我觉得有必要知道编译器什么时候改变我背后的东西.如果我在分析中是正确的,那么所有按位运算符都会提升为4字节整数吗?为什么一些签名和一些未签名?我很困惑!
编辑:我总是得到肯定或总是得到负值的假设是错误的.但是由于错误,我理解真正发生的事情,这要归功于下面的重要答案.
c++ bitwise-operators integer-promotion unsigned-integer signed-integer
以下程序:
#include <iostream>
#include <string>
int main ()
{
unsigned char result1 {0};
unsigned char result2 {0};
result1 = (result1 - 1) % 8;
result2 = result2 - 1;
result2 = result2 % 8;
std::cout << "result1 is " << std::to_string (result1) << '\n';
std::cout << "result2 is " << std::to_string (result2) << '\n';
}
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
result1 is 255
result2 is 7
Run Code Online (Sandbox Code Playgroud)
为什么result1和result2的计算结果不同?
我尝试了几个编译器,但它们都产生相同的结果,所以这一定是我不明白的地方。
c++ ×2