c++ 左移/右移运算符总结

c++ 左移/右移运算符总结

逻辑移位和算数移位

  • 明确两种概念(逻辑移位和算数移位)
  • 逻辑移位和算数移位有区别,仅针对于有符号整数的左移/右移运算,对于无符号整数,没有这两者运算之间的差距

无符号整数

  • 采用逻辑移位,无论左移右移都用“0”填充

有符号整数

  • 逻辑移位即为有符号整数进行左移运算,高位舍掉,低位进行补“0”
  • 算数移位即为有符号整数进行右移运算,低位舍掉,高位补“符号位”

常数

  • 对于常数,只要左移超过31位,就是0

在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;

template<class T>
void printf_2(T& x) {
    
    
	cout << x << "的二进制:" << bitset<1 * 8>(x) << endl; // sizeof(x)
}

int main() {
    
    
	unsigned short a = 0110;
	int b = 0110;
	int c = -0110;
	printf_2(a);
	a = a << 4; // 左移 逻辑移位
	printf_2(a);

	printf_2(b);
	printf_2(c);
	c = c >> 3; // 右移 算术移位

	// 算术移位,空出的部分用符号位填补
	// 逻辑移位 则用0填补

	printf_2(c);
	//cout << bitset<sizeof(b)>  << endl;
}

猜你喜欢

转载自blog.csdn.net/lr_shadow/article/details/108813673