Shift operation skills

Shift operation skills

shift left<<

Shift the binary number to the left, discard the high bit overflow, and fill the position with 0

int a = 11;
int b = a << 1;
//b = 22
// 位移前: 0000 1011
// 位移后: 0001 0110
int b = 5;
int c = b << 2;
//c = 20

Conclusion:
Shifting a number to the left by 1 bit is to multiply by 2, and shifting to the left by n bits is to multiply by 2 to the nth power.

Shift right>>

In the right shift operation, the unsigned number is shifted to the right and the high bit is filled with 0, the sign bit of the signed number is moved together, the positive number is filled with 0, and the negative number is filled with 1.

int a = 16;
int b  = a >> 3;
// b = 2
int b = -32;
int c = b >> 4
// c = 2

Conclusion:
Shifting right by n bits is dividing by 2 to the nth power, and when the obtained quotient is not an integer, take an integer.

Guess you like

Origin blog.csdn.net/weixin_42202992/article/details/132076148