How do I set, clear and toggle a bit in Rust?
Rust has both bit-twiddling operators and binary format printing (very helpful for debugging):
fn bit_twiddling(original: u8, bit: u8) {
let mask = 1 << bit;
println!(
"Original: {:b}, Set: {:b}, Cleared: {:b}, Toggled: {:b}",
original,
original | mask,
original & !mask,
original ^ mask
);
}
fn main() {
bit_twiddling(0, 3);
bit_twiddling(8, 3);
}
It also has the compound assignment variants (|=, &= and ^=).
The book has some more information