简介
按位移位运算符是右移位运算符 (>>) ,它将 shift 表达式 的位移动到右侧,左移运算符 (<<) ,这将向左移动 移位表达式 的位数。
语法
移位表达式 <<加法表达式
shift-expression >> additive-expression
备注
重要
以下说明和示例在 Windows 上适用于 x86 和 x64 体系结构。 对于 ARM 设备,左移运算符和右移位运算符的实现在很大程度上是不同的。
左移
左移运算符使 shift 表达式 中的位向左移动由 加法表达式 指定的位置数。 因移位运算而空出的位上将用零填充。 左移是逻辑移动(从末端移掉的位将被舍弃,包括符号位)
以下示例将显示使用无符号数字的左移运算。 该示例通过将值表示为 bitset 来显示对位的操作。
#include <iostream>
#include <bitset>
using namespace std;
int main() {
unsigned short short1 = 4;
bitset<16> bitset1{
short1}; // the bitset representation of 4
cout << bitset1 << endl; // 0b00000000'00000100
unsigned short short2 = short1 << 1; // 4 left-shifted by 1 = 8
bitset<16> bitset2{
short2};
cout << bitset2 << endl; // 0b00000000'00001000
unsigned short short3 = short1 << 2; // 4 left-shifted by 2 = 16
bitset<16> bitset3{
short3};
cout << bitset3 << endl; // 0b00000000'00010000
}
如果你左移有符号的数字,以至于符号位受影响,则结果是不确定的。 下面的示例演示了将1位左移到符号位位置时所发生的情况。
#include <iostream>
#include <bitset>
using namespace std;
int main() {
short short1 = 16384;
bitset<16> bitset1(short1);
cout << bitset1 << endl; // 0b01000000'00000000