โ† Cisco questions

Reverse Bits of an Unsigned Char Variable

Filed under Cisco

Free read 1 of 3

Iterate 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

  1. Iterate 8 times. In each iteration, extract the least significant bit of the input and shift it into the result.

Solution

O(1) time, O(1) space

Python
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.