0
0
Embedded Cprogramming~10 mins

XOR for toggling bits in Embedded C - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - XOR for toggling bits
Start with initial bits
Apply XOR with toggle mask
Bits where mask=1 flip
Bits where mask=0 stay same
Result: toggled bits
End
XOR flips bits where the mask has 1s and leaves others unchanged, toggling bits step-by-step.
Execution Sample
Embedded C
unsigned char bits = 0b10101010;
unsigned char mask = 0b00001111;
bits = bits ^ mask;
This code toggles the lower 4 bits of 'bits' using XOR with 'mask'.
Execution Table
Stepbits (binary)mask (binary)XOR Result (binary)Explanation
1101010100000111110100101Initial bits XOR mask toggles lower 4 bits
2101001010000111110101010Applying XOR again toggles lower 4 bits back
Exit---No more toggling, bits restored to original
💡 After two toggles, bits return to original value, showing XOR toggling effect
Variable Tracker
VariableStartAfter 1After 2Final
bits10101010101001011010101010101010
mask00001111000011110000111100001111
Key Moments - 2 Insights
Why does applying XOR twice with the same mask restore the original bits?
Because XOR flips bits where mask=1, doing it twice flips them back, as shown in execution_table rows 1 and 2.
What happens to bits where the mask has 0?
Those bits stay the same since XOR with 0 leaves bits unchanged, as seen in the unchanged upper 4 bits in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'bits' after the first XOR operation?
A10101010
B10100101
C00001111
D11111111
💡 Hint
Check execution_table row 1 under 'XOR Result (binary)'
At which step does 'bits' return to its original value?
AStep 1
BExit
CStep 2
DNever
💡 Hint
Look at execution_table rows 1 and 2 for 'bits' values
If the mask was 0b11110000 instead, which bits would toggle?
AUpper 4 bits
BAll bits
CLower 4 bits
DNo bits
💡 Hint
Mask bits set to 1 determine which bits toggle; see variable_tracker for mask bits
Concept Snapshot
XOR toggles bits where mask bits are 1.
Applying XOR twice with same mask restores original bits.
Bits with mask=0 stay unchanged.
Use: bits = bits ^ mask;
Common in embedded C for bit toggling.
Full Transcript
This visual execution shows how XOR toggles bits in embedded C. Starting with bits 0b10101010 and mask 0b00001111, XOR flips the lower 4 bits. After the first XOR, bits become 0b10100101. Applying XOR again with the same mask flips those bits back to 0b10101010. Bits where mask is 0 remain unchanged throughout. This demonstrates XOR's property of toggling bits and restoring original values when applied twice with the same mask.