bitops
nimony/lib/std/bitops.nim
This module implements a series of low-level bit manipulation procedures over the fixed-width unsigned integers uint8, uint16, uint32 and uint64 -- or any type that satifies the BitInteger concept.
The procedures are generic and constrained by the BitInteger concept below, which lists exactly the bitwise and shift operators the algorithms rely on. The bodies are written against those operations only (plus a runtime sizeof to recover the bit width), so they lower cleanly to C, LLVM and JS alike, and any type providing the operator set is accepted.
Bit indices are 0-based and, for the rotate procedures, the shift amount is taken modulo the bit width so any amount is well defined.
type BitInteger = concept func and(x: Self, y: Self): Self func or(x: Self, y: Self): Self func xor(x: Self, y: Self): Self func not(x: Self): Self func shl(x: Self, y: int64): Self func shr(x: Self, y: int64): Self func -(x: Self, y: Self): Self func ==(x: Self, y: Self): bool
func countSetBits(x: T): int64Counts the set bits in
x(the Hamming weight / population count).func popcount(x: T): int64Alias for
countSetBits.func parityBits(x: T): int64Returns
1whenxhas an odd number of set bits, otherwise0.func firstSetBit(x: T): int64Returns the 1-based index of the least-significant set bit of
x. Returns0whenxis0.func trailingZeroBits(x: T): int64Returns the number of trailing zero bits of
x, or the bit width whenxis0.func leadingZeroBits(x: T): int64Returns the number of leading (most-significant) zero bits of
x, or the bit width whenxis0.func bitand(x: T; y: T): TComputes the
andofxandy.func bitor(x: T; y: T): TComputes the
orofxandy.func bitxor(x: T; y: T): TComputes the
xorofxandy.func bitnot(x: T): TComputes the bitwise complement of
x.func rotateLeftBits(v: T; amount: int64): TRotates the bits of
vleft byamountpositions (taken modulo the bit width).func rotateRightBits(v: T; amount: int64): TRotates the bits of
vright byamountpositions (taken modulo the bit width).func setBit(v: var T; bit: int64)Sets the bit at position
bitofvto1.func clearBit(v: var T; bit: int64)Clears the bit at position
bitofvto0.func flipBit(v: var T; bit: int64)Toggles the bit at position
bitofv.func testBit(v: T; bit: int64): boolReturns
truewhen the bit at positionbitofvis set.