Translation Notice
This article was machine-translated using DeepSeek-R1.
- Original Version: Authored in Chinese by myself
- Accuracy Advisory: Potential discrepancies may exist between translations
- Precedence: The Chinese text shall prevail in case of ambiguity
- Feedback: Technical suggestions regarding translation quality are welcomed
For the <<
and >>
operators, we can state:
$a<
$a>>b=a/2^b$
But for >>>
… it’s more complicated.
How do these bitwise operations work in computers?
As we know, integers are stored in binary format in computers:
$0 = (0)_2$
$4 = (100)_2$
$8 = (1000)_2$
$20 = (10100)_2$
$666 = (1010011010)_2$
Left Shift (<<
)
$a << b$ means appending $b$ zeros to the binary representation of $a$, hence $a<
Take $20$ as an example:
$20 << 1 = (10100)_2 << 1 = (101000)_2 = 40$,
$20 << 2 = (10100)_2 << 2 = (1010000)_2 = 80$.
Right Shift (>>
)
>>
is the opposite of <<
. $a>>b$ means removing $b$ bits from the end of $a$’s binary representation, hence $a>>b=a/2^b$
Still using $20$ as an example:
$20 >> 1 = (10100)_2 >> 1 = (1010)_2 = 10$,
$20 >> 2 = (10100)_2 >> 2 = (101)_2 = 5$
What if the end bits aren’t zeros? Still remove them:
$21 >> 1 = (10101)_2 >> 1 = (1010)_2 = 10$