fn set_bit(num: u8, pos: u8) -> u8 {
num | (1 << pos) // turn bit at pos to 1
}
fn clear_bit(num: u8, pos: u8) -> u8 {
num & !(1 << pos) // turn bit at pos to 0
}
fn toggle_bit(num: u8, pos: u8) -> u8 {
num ^ (1 << pos) // flip bit at pos
}
fn main() {
let mut num: u8 = 0b00001010; // 10 decimal
println!("Initial: {:08b}", num);
num = set_bit(num, 0);
println!("After set bit 0: {:08b}", num);
num = clear_bit(num, 3);
println!("After clear bit 3: {:08b}", num);
num = toggle_bit(num, 2);
println!("After toggle bit 2: {:08b}", num);
println!("Final decimal: {}", num);
}num | (1 << pos) // turn bit at pos to 1
set bit by OR with mask having 1 at pos
num & !(1 << pos) // turn bit at pos to 0
clear bit by AND with mask having 0 at pos
num ^ (1 << pos) // flip bit at pos
toggle bit by XOR with mask having 1 at pos
apply clear bit operation
num = toggle_bit(num, 2);
apply toggle bit operation
Initial: 00001010
After set bit 0: 00001011
After clear bit 3: 00000011
After toggle bit 2: 00000111
Final decimal: 7