.bitnot
- two's complement bitwise NOT
.bitand
- two's complement bitwise AND
.bitor
- two's complement bitwise OR
.bitxor
- two's complement bitwise exclusive OR
.bit?
- is a bit set?
.bitset
- set a bit
.bitclear
- clear a bit
.bitpow2
- value of bit
.bitnot
, .bitand
,
.bitor
and .bitxor
perform
bitwise operations on integers. They perform the given action on
each of the bits in the integers according to the following truth
tables:
.bitnot | 0 | 1 | .bitand | 0 | 1 | --------+---+---+ --------+---+---+ | 1 | 0 | 0 | 0 | 0 | --------+---+---+ --+---+---+ 1 | 0 | 1 | --------+---+---+ .bitor | 0 | 1 | .bitxor | 0 | 1 | --------+---+---+ --------+---+---+ 0 | 0 | 1 | 0 | 0 | 1 | --+---+---+ --+---+---+ 1 | 1 | 1 | 1 | 1 | 0 | --------+---+---+ --------+---+---+
Note that bit 31, the most significant bit, is the sign bit, so if it is set the corresponding integer will be negative.
.bit?
, .bitset
and
.bitclear
test, set or clear a
specified bit in an integer. While they can be (and are) written in
terms of the bitwise functions, it is often easier to think in terms
of bit numbers.
Bits are numbered from 0 to 31, with 0 being the least significant and 31 being the signed, most significant bit. Note that the zero-origin convention is used, i.e., the bits are not numbered 1 to 32.
To use these functions, push the number to test ot set on the stack, then push the bit number. Bit numbers below zero will be considered zero; bit numbers over 31 will be considered 31.
.bitset
always returns an integer with the specified bit set. (It is
similar to .bitor
.) .bitclear
always returns an integer with the
specified bit set. (It is similar to .bitnot
followed by
.bitand
.)
.bit?
returns zero if the specified bit is clear, otherwise it returns
nonzero. (It should not be assumed that this nonzero value is 1.)
The last function, .bitpow2
, returns 2^n for
n in the range 0 to 31,
with 2^31 being -2147483648 since it is a sign bit. This function
is used by the single-bit functions and is useful enough in its own
right to be made public in the library.
5 (0101) .bitnot (result is -6) (1111...1010) 5 (0101) 12 (1100) .bitand (result is 4) (0100) 5 (0101) 12 (1100) .bitor (result is 13) (1101) 5 (0101) 12 (1100) .bitxor (result is 9) (1001) 5 -1 (1111...1111) .bitand (result is 5) (-1 is the identity value) 5 0 (0) .bitor (result is 0) (0 is the identity value) 5 5 .bitxor (result is 0) (exclusive OR can be used to test equality) 5 (0101) 0 .bit? (result is nonzero) 5 (0101) 1 .bit? (result is 0) 5 (0101) 1 .bitset (result is 7) (0111) 5 (0101) 2 .bitclear (result is 1) (0001) 5 .bitpow2 (result is 32) (100000)