Challenge - 5 Problems
Bitwise Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output after setting the 3rd bit of 0b0101?
Consider the following Rust code that sets a specific bit in a number. What will be printed?
DSA Rust
fn main() {
let mut num = 0b0101u8;
let bit_position = 3;
num |= 1 << bit_position;
println!("{:08b}", num);
}Attempts:
2 left
💡 Hint
Setting a bit means turning it to 1 using OR operation.
✗ Incorrect
The original number is 0b0101 (decimal 5). Setting the 3rd bit (counting from 0) means setting bit 3 to 1. Bit 3 corresponds to 1 << 3 = 0b1000. OR operation 0b0101 | 0b1000 = 0b1101 (decimal 13). Printed as 8 bits: 00001101.
❓ Predict Output
intermediateWhat is the output after clearing the 2nd bit of 0b1111?
Look at this Rust code that clears a specific bit. What will it print?
DSA Rust
fn main() {
let mut num = 0b1111u8;
let bit_position = 2;
num &= !(1 << bit_position);
println!("{:04b}", num);
}Attempts:
2 left
💡 Hint
Clearing a bit means turning it to 0 using AND with NOT mask.
✗ Incorrect
Original number is 0b1111 (decimal 15). Clearing bit 2 means setting bit 2 to 0. Bit 2 mask is 1 << 2 = 0b0100. NOT mask is 0b1011. AND operation 0b1111 & 0b1011 = 0b1011 (decimal 11). Printed as 4 bits: 1011.
❓ Predict Output
advancedWhat is the output after toggling the 1st bit of 0b1010?
This Rust code toggles a specific bit. What will it print?
DSA Rust
fn main() {
let mut num = 0b1010u8;
let bit_position = 1;
num ^= 1 << bit_position;
println!("{:04b}", num);
}Attempts:
2 left
💡 Hint
Toggling flips the bit: 0 to 1 or 1 to 0 using XOR.
✗ Incorrect
Original number is 0b1010 (decimal 10). Toggling bit 1 flips bit 1. Bit 1 mask is 1 << 1 = 0b0010. XOR 0b1010 ^ 0b0010 = 0b1000 (decimal 8). Printed as 4 bits: 1000.
🔧 Debug
advancedWhat error does this Rust code produce when trying to set a bit?
Identify the error when running this code snippet.
DSA Rust
fn main() {
let mut num = 0b0010u8;
let bit_position = 8;
num |= 1 << bit_position;
println!("{:08b}", num);
}Attempts:
2 left
💡 Hint
Shifting by a number equal or larger than the bit size of the type causes panic.
✗ Incorrect
u8 has 8 bits indexed 0 to 7. Shifting 1 << 8 is invalid and causes panic at runtime in Rust with overflow check enabled.
🧠 Conceptual
expertHow many bits are set after toggling bits 0, 1, and 2 on 0b0000?
Starting with 0b0000, toggle bits at positions 0, 1, and 2 one by one. How many bits are set to 1 at the end?
Attempts:
2 left
💡 Hint
Toggling a bit flips it from 0 to 1 or 1 to 0.
✗ Incorrect
Starting from 0b0000, toggling bit 0 sets it to 1 (0b0001), toggling bit 1 sets it to 1 (0b0011), toggling bit 2 sets it to 1 (0b0111). Total bits set: 3.
