0
0
Embedded Cprogramming~5 mins

XOR for toggling bits in Embedded C - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does XOR operation do when used to toggle a bit?
XOR flips the bit: if the bit is 0, it becomes 1; if it is 1, it becomes 0.
Click to reveal answer
beginner
How do you toggle the 3rd bit of a variable 'x' using XOR in C?
Use the expression: x = x ^ (1 << 2); because bits start at 0 from the right.
Click to reveal answer
intermediate
Why is XOR preferred for toggling bits instead of using OR or AND?
Because XOR flips bits without affecting others, while OR sets bits and AND clears bits.
Click to reveal answer
intermediate
What happens if you XOR the same bit twice?
The bit returns to its original value because XORing twice cancels the toggle.
Click to reveal answer
beginner
Write a C code snippet to toggle bits 0 and 1 of a byte variable 'flags'.
flags = flags ^ 0x03; // 0x03 is binary 00000011, toggles bits 0 and 1
Click to reveal answer
What is the result of toggling bit 1 of 0b00000100 using XOR?
A0b00000110
B0b00000100
C0b00000010
D0b00000000
Which operator is used to toggle bits in embedded C?
AAND (&)
BOR (|)
CXOR (^)
DNOT (~)
If you XOR a bit with 0, what happens to the bit?
AIt becomes 0
BIt becomes 1
CIt toggles
DIt stays the same
What does the expression (1 << 4) represent?
ABit mask with bit 4 set
BNumber 4
CBit mask with bit 1 set
DShift right by 4 bits
Toggling the same bit twice results in:
ABit set to 1
BOriginal bit value
CUndefined behavior
DBit set to 0
Explain how XOR can be used to toggle a specific bit in a byte variable.
Think about how XOR changes 0 to 1 and 1 to 0.
You got /3 concepts.
    Describe why XOR is better than AND or OR for toggling bits.
    Consider what happens to bits not targeted by the operation.
    You got /4 concepts.