Bitwise
Functions for doing bitwise operations.
Bitwise operations only work on 32-bit integers.
When an Int
is passed to a bitwise operation, only the 32 least significant bits are used.
Bitwise AND
Bitwise OR
Bitwise XOR
Flip each bit individually, often called bitwise NOT
Count the number of leading zero bits in an integer.
countLeadingZeros 0 == 32
countLeadingZeros 1 == 31
countLeadingZeros 0xFFFF == 16
Bit Shifts
Note: Because bitwise operations only work on 32-bit integers, the shift distance is effectively limited to 31.
If you shift by n
, only the lowest 5 bits of n
will be used and the binary will be shifted by modBy 32 n
.
For example, the following two commands perform the same operation:
Bitwise.shiftLeftBy 1 10
Bitwise.shiftLeftBy 33 10
Shift bits to the left by a given offset, filling new bits with zeros. This can be used to multiply numbers by powers of two.
shiftLeftBy 1 5 == 10
shiftLeftBy 5 1 == 32
Shift bits to the right by a given offset, filling new bits with whatever is the topmost bit. This can be used to divide numbers by powers of two.
shiftRightBy 1 32 == 16
shiftRightBy 2 32 == 8
shiftRightBy 1 -32 == -16
This is called an arithmetic right shift, often written >>
, and
sometimes called a sign-propagating right shift because it fills empty spots
with copies of the highest bit.
Shift bits to the right by a given offset, filling new bits with zeros.
shiftRightZfBy 1 32 == 16
shiftRightZfBy 2 32 == 8
shiftRightZfBy 1 -32 == 2147483632
This is called an logical right shift, often written >>>
, and
sometimes called a zero-fill right shift because it fills empty spots with
zeros.