std/bits

std/bits 模块提供低层位的按位运算,包括循环移位(rotation)、位计数(population count)和按位反转。

概览

使用方法

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)。