Bit Operations
Bit-oriented helpers in std.bit and low-level integer operations.
std.bit contains helpers for bit operations and compiler-backed intrinsics.
Its helpers are generic over the builtin Integer marker interface, so they
work across primitive integer widths while rejecting bool and user structs.
The language also has built-in bitwise operators:
let flags = 0b1010;
let masked = flags & 0b0010;
let shifted = masked << 1;
| Operator | Purpose |
|---|---|
& | bitwise and |
| ` | ` |
^ | bitwise xor |
~ | bitwise not |
<< | shift left |
>> | shift right |
Use std.bit for reusable helpers and the language operators for direct
integer or vector expressions. See
Operators for precedence and operand
rules, and Interfaces for Integer,
Signed, and Unsigned.
Integer is implemented by primitive integer types such as i32, u64,
isize, and usize. bool does not implement Integer.
swap_bytes follows the LLVM width rule: the integer width must be divisible
by 16, so i8 and u8 are not valid for byte swapping.
import std.bit;
fn mirror<T: Integer>(value: T) -> T {
return bit.reverse_bits(value);
}
fn main() {
assert bit.swap_bytes(0x0102 as u16) == (0x0201 as u16);
assert mirror<u8>(0b10110000 as u8) == (0b00001101 as u8);
assert bit.count_ones(0b10110100 as u8) == (4 as u8);
assert bit.rotate_left(0b10000001 as u8, 10 as u8) == (0b00000110 as u8);
}
| Function | Signature | Purpose |
|---|---|---|
swap_bytes | swap_bytes<T: Integer>(x: T) -> T | Reverse byte order for integer widths divisible by 16. |
reverse_bits | reverse_bits<T: Integer>(x: T) -> T | Reverse all bits in the value. |
count_ones | count_ones<T: Integer>(x: T) -> T | Count set bits and return the count in the same integer type. |
leading_zeros | leading_zeros<T: Integer>(x: T) -> T | Count zero bits before the highest set bit. |
trailing_zeros | trailing_zeros<T: Integer>(x: T) -> T | Count zero bits after the lowest set bit. |
rotate_left | rotate_left<T: Integer>(x: T, n: T) -> T | Rotate bits left. |
rotate_right | rotate_right<T: Integer>(x: T, n: T) -> T | Rotate bits right. |