std/bits

std/bits 模組提供低階位元操作,包括旋轉(rotations)、位元計數(population counts)和位元反轉。

概覽

使用方法

import "std/bits.zc"

fn main() {
    let a: u32 = 0x80000001;
    
    // 將 32 位元整數向左旋轉 1 位元
    let rotated = Bits::rotl32(a, 1); // 0x00000003
    
    // 統計設置的位元(位元計數)
    let count = Bits::popcount32(0b1011); // 3
    
    // 反轉位元組順序 (bswap)
    let swapped = Bits::bswap32(0x12345678); // 0x78563412
}

方法

位元旋轉

方法簽名說明
rotl[N]Bits::rotl[N](n: u[N], c: u[N]) -> u[N]將 n 向左旋轉 c 位元 (N=8, 16, 32, 64, 128)。
rotr[N]Bits::rotr[N](n: u[N], c: u[N]) -> u[N]將 n 向右旋轉 c 位元 (N=8, 16, 32, 64, 128)。

位元計數

方法簽名說明
popcount[N]Bits::popcount[N](n: u[N]) -> u[N]返回 n 中設置的位元(1)數量 (N=8, 16, 32, 64, 128)。

領先/尾隨零計數

方法簽名說明
clz[N]Bits::clz[N](n: u[N]) -> u[N]返回領先零位元的數量 (N=8, 16, 32, 64, 128)。
ctz[N]Bits::ctz[N](n: u[N]) -> u[N]返回尾隨零位元的數量 (N=8, 16, 32, 64, 128)。

位元組交換與位元反轉

方法簽名說明
bswap[N]Bits::bswap[N](n: u[N]) -> u[N]反轉 n 的位元組順序 (N=16, 32, 64, 128)。
reverse_bits[N]Bits::reverse_bits[N](n: u[N]) -> u[N]反轉 n 的位元順序 (N=8, 16, 32, 64, 128)。