std/bits — Bit manipulation¶
import std/bits
Bit-level utilities: rotations, population count, parity, and bit reversal, in
8- and 16-bit widths. These complement the language’s built-in bitwise
operators (&, |, ^, ~) with operations that have no single
operator.
Rotation¶
- @rotl8($val: u8, $n: u8) -> u8¶
Rotate the 8-bit value
$valleft by$nbit positions (bits shifted out of the top re-enter at the bottom).
- @rotr8($val: u8, $n: u8) -> u8¶
Rotate the 8-bit value
$valright by$nbit positions.
- @rotl16($val: u16, $n: u8) -> u16¶
Rotate the 16-bit value
$valleft by$nbit positions.
- @rotr16($val: u16, $n: u8) -> u16¶
Rotate the 16-bit value
$valright by$nbit positions.
Counting and parity¶
- @popcount8($val: u8) -> u8¶
Return the number of set bits (1s) in the 8-bit value
$val.
- @popcount16($val: u16) -> u8¶
Return the number of set bits in the 16-bit value
$val.
- @parity8($val: u8) -> u8¶
Return the parity of
$val:1if it has an odd number of set bits,0if even.
Reversal¶
- @reverse8($val: u8) -> u8¶
Return
$valwith its 8 bits in reverse order (bit 0 ↔ bit 7, etc.).
- @reverse16($val: u16) -> u16¶
Return
$valwith its 16 bits in reverse order.
Example¶
import std/bits
@main {
ram imut $r: u8 = @rotl8(0x81, 1) # rotate left by 1: 1000_0001 -> 0000_0011 = 0x03
ram imut $c: u8 = @popcount8(0xF0) # count the set bits in 1111_0000 = 4
ram imut $v: u8 = @reverse8(0x01) # reverse the bit order: 0x01 -> 0x80
loop * { }
}