fn main() {
let x = 29;
let y = 8;
let result = x & (y - 1);
println!("{}", result);
}The expression x & (y - 1) is equivalent to x % y when y is a power of two. Here, y = 8, so y - 1 = 7 (binary 0111). Bitwise AND with 7 extracts the last 3 bits of x. For x = 29 (binary 11101), the last 3 bits are 101, which is 5 in decimal.
Bit manipulation instructions like AND, OR, XOR, and shifts typically execute in fewer CPU cycles because they do not involve carry or borrow logic, unlike addition or subtraction. This makes them faster on many processors.
fn main() {
let x: u8 = 1;
let y = x << 8;
println!("{}", y);
}In Rust, shifting a value by an amount equal to or greater than the number of bits in its type causes a compile-time error. Here, u8 has 8 bits, so shifting by 8 is invalid.
The least significant bit (LSB) of a number indicates if it is odd (1) or even (0). Using bitwise AND with 1 extracts this bit. Option A correctly checks if num & 1 equals 1.
Modulus operations with powers of two can be replaced by bitwise AND with n-1, which is much faster. This is especially beneficial inside tight loops where performance matters.
