Reverse Bits of an Unsigned Char Variable
Filed under Cisco
Free read 1 of 3Iterate 8 times. In each iteration, extract the least significant bit of the input and shift it into the result.
The question
Reverse the bits of an unsigned char (8-bit integer) without using arrays.
Constraints
- No arrays allowed.
- Must operate on 8 bits.
- Use bitwise operators.
Examples
- Input
- 00000011 (3)
- Output
- 11000000 (192)
- Why
- Bits are reversed positionally.
Approach
Iterate 8 times. In each iteration, extract the least significant bit of the input and shift it into the result.
Shift the result left to make room, then OR with the extracted bit. Shift the input right to process the next bit.
Ensure the final value is treated as an 8-bit unsigned integer.
Solution
O(1) time, O(1) space
def reverse_bits(n):
res = 0
for _ in range(8):
res = (res << 1) | (n & 1)
n >>= 1
return res
Tips
- What they are testing: Test with 0, 255, and values with alternating bits.
- Common mistake: Forgetting to mask the result to 8 bits if the language uses larger integer types.
Related Cisco questions
Collected from public candidate posts and coding forums. Updated Nov 2026.