Bitwise Operators
December 21, 2022
note-to-self
Bitwise Operators
$a & $b And Bits that are set in both $a and $b are set.
$a | $b Or Bits that are set in either $a or $b are set.
$a ^ $b Xor Bits that are set in $a or $b but not both are set.
~ $a Not Bits that are set in $a are not set, and vice versa.
$a << $b Shift left Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $b Shift right Shift the bits of $a $b steps to the right (each step means "divide by two")
& (bitwise logical and)
If both binary numbers have a 1
in the same place, it's a 1
. If one place has a 1
and one place has a 0
, in &
you keep the 0
.
17 & 6 = 0
# 00010001 17
# 00000110 6
# 00000000 0
| (bitwise logical or)
If both binary numbers have a 1
in the same place, it's a 1
. If one place has a 1
and one place has a 0
, in |
you keep the 1
.
17 | 6 = 23
# 00010001 17
# 00000110 6
# 00010111 23
^ (bitwise logical exclusive or)
If both binary numbers have the same value in the same place, whether 1
or 0
, it's a 0
. If they differ, in ^
it is then 1
.
17 ^ 23 = 6
# 00010001 17
# 00010111 23
# 00000110 6
<<
17 << 1 = 34 (1 step; each _step_ means multiply by _2_ (it's not 17 * 1, it's 17 * 2))
17 << 2 = 68 (2 steps; each _step_ means multiply by 2; 17 * 2 * 2)
These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.