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.
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.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
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 see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
