Clarify two concepts (logical shift and arithmetic shift)
There is a difference between logical shift and arithmetic shift, which is only for the left/right shift operations of signed integers. For unsigned integers, there is no difference between the two operations.
Unsigned integer
Use logical shift, fill with "0" regardless of left shift and right shift
Signed integer
Logical shift is the left shift operation of signed integer, the high bit is discarded, and the low bit is filled with "0"
Arithmetic shift is the right shift operation of signed integer, the low bit is rounded off, and the high bit is filled with "sign bit"
constant
For a constant, as long as the left shift exceeds 31 bits, it is 0
#include<bits/stdc++.h>usingnamespace std;template<classT>voidprintf_2(T& x){
cout << x <<"的二进制:"<< bitset<1*8>(x)<< endl;// sizeof(x)}intmain(){
unsignedshort 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;}