Reflected Binary

Given a number, implement the conversion from binary to reflected binary.

Reflected binary is an alternate binary representation where numbers in sequence only change a single bit at a time. For example, the numbers 0 through 4 are represented in binary and reflected binary below. This is also known as Gray code.

Number
0
1
2
3
4

Binary
0000
0001
0010
0011
0100

Reflected
0000
0001
0011
0010
0110

uint toReflected(uint x) {
  return x ^ (x >> 1)
}
Scroll to top