
Bitwise operations are a core skill when working with low-level systems, embedded software, and device control. Interviewers often use register-style questions to test whether you can manipulate individual bits precisely and safely.
Explain how to use bitwise operations to manipulate specific bits in a hardware-style register represented as an integer.
Your answer should cover:
The interviewer expects a practical conceptual explanation, not hardware-specific electrical details. You should be able to describe the common operators (&, |, ^, ~, <<, >>), show small code examples, and explain common mistakes such as using the wrong mask or accidentally modifying other bits.
A bit mask is an integer whose binary representation selects specific bit positions. It is usually created with a left shift such as 1 << k, which places a 1 at bit position k.
mask = 1 << 3 # 0b1000
Setting a bit uses OR, clearing a bit uses AND with an inverted mask, toggling uses XOR, and reading uses AND followed by a comparison or shift. These operations target one bit while preserving the others.
reg |= mask
reg &= ~mask
reg ^= mask
bit = (reg & mask) != 0
Left shift moves bits toward more significant positions and is commonly used to build masks. Right shift moves bits toward less significant positions and is useful when extracting a bit field after masking.
field = (reg >> 4) & 0b111
A bit field is a group of adjacent bits that encode a small value. To update a field, first clear those bits with a mask, then insert the new value by shifting it into position and OR-ing it in.
reg = (reg & ~(0b111 << 4)) | ((value & 0b111) << 4)
The main goal in register manipulation is to change only the intended bits. Good masking ensures that all other bits remain unchanged, which is critical in systems code where each bit may control a different feature.