Set an even-parity bit in a byte's MSB
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests bit manipulation, parity and xor.
Bytes sent over a noisy link often carry a parity bit so the receiver can detect a flipped bit. In this scheme the parity bit is the most significant bit (bit 7, value 128) and the code uses even parity: the full byte must contain an even number of 1 bits.
Implement:
def set_parity_bit(b: int) -> int: ...
-
bis a byte, an integer in[0, 255]. Bits 0–6 are data; bit 7 may already hold anything. - Return a byte whose bits 0–6 are unchanged and whose bit 7 is chosen so the total number of
1bits is even. - Change only the MSB. Use bit manipulation (masks, shifts, XOR), not string conversion.
- Raise
ValueErrorifbis outside[0, 255].
Examples
| Input | Data bits (0–6) | 1s in data | Output |
|---|---|---|---|
0b00010110 (22) |
0010110 |
3 |
0b10010110 (150) |
0b10000110 (134) |
0000110 |
2 |
0b00000110 (6) |
In the second example the incoming MSB was 1, which would make the count odd, so it is cleared.
Be ready to extend the function to odd parity, to whole buffers of bytes, and to the receiver's check.
Clarifying questions
- Is the input ever outside
0..255, such as negative or larger values, and should those raise? - Should the function ignore the incoming bit 7 completely when counting?
- Is a lookup table acceptable, or must it compute the parity each time?
- Is Python's
int.bit_count()allowed, or should the parity be computed with XORs?
What a strong answer covers
- Masks the data bits with
b & 0x7F, computes their parity (XOR folding:x ^= x >> 4,x ^= x >> 2,x ^= x >> 1, thenx & 1), and sets bit 7 to that parity. - Returns
(b & 0x7F) | (parity << 7)so bits 0 to 6 never change. -
O(1)time; a 128-entry table is an option for buffers. - Tests both table rows,
0,255, and every value from0to255against a reference count.
Follow-ups
- Switch to odd parity.
- Apply it to a whole buffer of bytes efficiently.
- Write the receiver's check, and say which errors parity cannot detect.
Where it's asked
What it tests
bit manipulation · parity · xor
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
