Bits
module Bits
The Bits module provides bitwise operations on Integer.
Integers are arbitrary precision, and a negative one behaves as if it were written in infinite-precision two's complement — so Bits.not(0) is -1 and Bits.and(-1, 255) is 255, with no word size to overflow. Shifts and bit indices count from bit 0 (the least significant bit).
and
and(a: Integer, b: Integer) -> Integer
Bitwise AND of a and b.
Parameters
ab
Examples
Bits.and(0b1100, 0b1010) # => 0b1000
Bits.and(0xff, 0x0f) # => 15
or
or(a: Integer, b: Integer) -> Integer
Bitwise OR of a and b.
Parameters
ab
Examples
Bits.or(0b1100, 0b1010) # => 0b1110
xor
xor(a: Integer, b: Integer) -> Integer
Bitwise exclusive OR of a and b.
Parameters
ab
Examples
Bits.xor(0b1100, 0b1010) # => 0b0110
not
not(a: Integer) -> Integer
Bitwise complement of a. Every integer is signed and unbounded, so this is always +-(a + 1)+ rather than a width-dependent mask.
Parameters
a
Examples
Bits.not(0) # => -1
Bits.not(5) # => -6
shiftLeft
shiftLeft(n: Integer, by: Integer) -> Integer
Shifts n left by by bits. Raises if by is negative.
Parameters
nby
Examples
Bits.shiftLeft(1, 8) # => 256
shiftRight
shiftRight(n: Integer, by: Integer) -> Integer
Shifts n right by by bits, propagating the sign — the result of shifting a negative number stays negative. Raises if by is negative.
Parameters
nby
Examples
Bits.shiftRight(256, 8) # => 1
Bits.shiftRight(-8, 1) # => -4
test?
test?(n: Integer, index: Integer) -> Bool
True when the bit at index of n is set. Raises if index is negative.
Parameters
nindex
Examples
Bits.test?(0b1000, 3) # => true
Bits.test?(0b1000, 0) # => false
set
set(n: Integer, index: Integer) -> Integer
n with the bit at index set. Raises if index is negative.
Parameters
nindex
Examples
Bits.set(0, 3) # => 8
clear
clear(n: Integer, index: Integer) -> Integer
n with the bit at index cleared. Raises if index is negative.
Parameters
nindex
Examples
Bits.clear(0b1111, 0) # => 14
toggle
toggle(n: Integer, index: Integer) -> Integer
n with the bit at index flipped. Raises if index is negative.
Parameters
nindex
Examples
Bits.toggle(0b1010, 0) # => 11