An integer is represented as a sequence of bits in memory. For interaction with humans, the computer has to display it as decimal digits, but all the calculations are carried out as binary. 123
in decimal is stored as 1111011
in memory.
The &
operator is a bitwise "And". The result is the bits that are turned on in both numbers. 1001 & 1100 = 1000
, since only the first bit is turned on in both.
The |
operator is a bitwise "Or". The result is the bits that are turned on in either of the numbers. 1001 | 1100 = 1101
, since only the second bit from the right is zero in both.
There are also the ^
and ~
operators, that are bitwise "Xor" and bitwise "Not", respectively. Finally there are the <<
, >>
and >>>
shift operators.
Under the hood, 123
is stored as either 01111011 00000000 00000000 00000000
or 00000000 00000000 00000000 01111011
depending on the system. Using the bitwise operators, which representation is used does not matter, since both representations are treated as the logical number 00000000000000000000000001111011
. Stripping away leading zeros leaves 1111011
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…