0
0
Rustprogramming~10 mins

Bitwise operators in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Bitwise operators
Start with two numbers
Apply bitwise operator (&, |, ^, <<, >>)
Operate on each bit position
Combine bits to form result
Output the result
Bitwise operators work on each bit of two numbers, combining them to produce a new number.
Execution Sample
Rust
let a = 6;  // 0b0110
let b = 3;  // 0b0011
let c = a & b;
println!("{}", c);
This code performs a bitwise AND on 6 and 3, then prints the result.
Execution Table
StepOperationBits of aBits of bBitwise & ResultDecimal Result
1Start01100011--
2Bit 3 (leftmost): 0 & 00000
3Bit 2: 1 & 01000
4Bit 1: 1 & 11111
5Bit 0 (rightmost): 0 & 10100
6Combine bits: 0010--00102
7Print result---2
💡 All bits processed, final result is 2
Variable Tracker
VariableStartAfter & operationFinal
a6 (0b0110)6 (0b0110)6 (0b0110)
b3 (0b0011)3 (0b0011)3 (0b0011)
c-2 (0b0010)2 (0b0010)
Key Moments - 3 Insights
Why does bit 2 result in 0 even though a has 1 there?
Because bitwise AND requires both bits to be 1. Here, b's bit 2 is 0, so 1 & 0 = 0 (see execution_table row 3).
Why is the final decimal result 2?
The combined bits after AND are 0010, which equals 2 in decimal (see execution_table row 6).
What happens if we use bitwise OR instead of AND?
Bits where either a or b is 1 become 1. The result would be 0111 (decimal 7), different from AND (see concept_flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the bitwise AND result at bit 1 (step 4)?
A2
B0
C1
D3
💡 Hint
Check execution_table row 4 under 'Bitwise & Result'
At which step does the combined bits form the final result?
AStep 6
BStep 5
CStep 7
DStep 3
💡 Hint
Look for 'Combine bits' in execution_table
If variable b was 7 (0b0111) instead of 3, what would be the decimal result after AND?
A7
B6
C3
D2
💡 Hint
AND with 6 (0110) and 7 (0111) keeps bits where both are 1
Concept Snapshot
Bitwise operators work on bits of numbers.
& (AND): 1 if both bits 1.
| (OR): 1 if either bit 1.
^ (XOR): 1 if bits differ.
<<, >> shift bits left/right.
Used for fast, low-level operations.
Full Transcript
This lesson shows how bitwise operators work in Rust. We start with two numbers, 6 and 3, and apply the bitwise AND operator. Each bit of the numbers is compared: only bits where both are 1 become 1 in the result. We trace each bit step-by-step, showing how the final result 2 is formed. Key points include understanding how bits combine and why the result is what it is. The quiz tests understanding of bitwise AND at specific bits and how changing inputs affects results.