Table of contents
What is stored in memory is two's complement.
So the shift operator is to shift the two's complement .
Take the left shift operator as an example: <<
left shift operator
For positive numbers:
#include<stdio.h>
int main()
{int a=10;
//00000000000000000000000000001010——补码 //正数原码反码补码相同
int b=a<<1; //左移1
printf("%d\n",b);
printf("%d\n",a);
return 0;
}
Process: Result:
Note: a does not change during this process.
For negative numbers:
#include<stdio.h>
int main()
{int a=-10;
//10000000000000000000000000001010——原码
//11111111111111111111111111110101——反码 //取反
//11111111111111111111111111110110——补码 //加一
int b=a<<1; //左移1
//11111111111111111111111111101100——补码
//11111111111111111111111111101011——反码 //减一
//10000000000000000000000000010100——原码 //取反
printf("%d\n",b);
printf("%d\n",a);
return 0;
}
Process: Result:
Note: What we print is the original code.
a remains unchanged.
Findings: 1. The rule is: discard on the left and fill in zeros on the right.
2. Shifting one bit to the left has the effect of multiplying by 2.
right shift operator
Right shift operators are divided into arithmetic right shift and logical right shift .
It depends on the compiler, arithmetic right shift is more common .
arithmetic right shift
#include<stdio.h>
int main()
{
int a = -1;
//10000000000000000000000000000001——原码
//11111111111111111111111111111110——反码
//11111111111111111111111111111111——补码
int b = a>>1;
//11111111111111111111111111111111——补码
//11111111111111111111111111111110——反码
//10000000000000000000000000000001——补码
printf("%d\n", b);
printf("%d\n", a);
return 0;
}
Process: Result:
logical shift right
#include<stdio.h>
int main()
{
int a = -1;
//10000000000000000000000000000001——原码
//11111111111111111111111111111110——反码
//11111111111111111111111111111111——补码
int b = a>>1;
//01111111111111111111111111111111——补码
//01111111111111111111111111111110——反码
//00000000000000000000000000000001——补码
printf("%d\n", b);
printf("%d\n", a);
return 0;
}
process:
Discovery: 1. Arithmetic right shift: the right side is discarded, and the left side complements the original sign bit.
2. Logical right shift: discard on the right and fill with zeros on the left.
Summarize
Left shift operator: discard on the left and pad with zeros on the right.
Arithmetic right shift: the right side is discarded, and the left side is filled with the original sign bit.
Logical shift right: discard on the right and pad with zeros on the left.
Note: There is no right/left shift of negative numbers.