std/bits
std/bits 模組提供低階位元操作,包括旋轉(rotations)、位元計數(population counts)和位元反轉。
概覽
- 跨平台:在不同架構上正確實現位元操作。
- 高效:使用優化的位元處理演算法。
- 全面:支援 8, 16, 32, 64 和 128 位元無符號整數.
- 端序工具:包含用於反轉位元組順序(端序交換)的函數。
使用方法
import "std/bits.zc"
fn main() {
let a: u32 = 0x80000001;
let rotated = Bits::rotl32(a, 1);
let count = Bits::popcount32(0b1011);
let swapped = Bits::bswap32(0x12345678);
}
方法
位元旋轉
| 方法 | 簽名 | 說明 |
| 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)。 |