Gray code

Gray code can reduce the errors of changing bits (or switches). It only needs to change 1 bit at a time to increments the decimal number.

Example 1

decimal binary gray code
5 101 111
6 110 101

From 5 to 6, binary has two bits changed, while gray code only changed 1 bit.

XOR is the method of converting binary to gray code. First we copy the most significant bit in binary to gray code’s 1st. Starting from 2nd most significant bit, we use XOR on the current bit and the previous bit.

Example 2

binary gray code
1, 0, 1 1, ?, ?
1, 0, 1 1, XOR(0, 1) = 1, ?
1, 0, 1 1, 1, XOR(1, 0) = 1
1, 0, 1 1, 1, 1
1, 1, 0 1, ?, ?
1, 1, 0 1, XOR(1, 1) = 0, ?
1, 1, 0 1, 0, XOR(1, 0) = 1
1, 1, 0 1, 0, 1

Binary and Decimal

To convert binary to decimal, simply multiply each bit by $2^{n}$ where n is the order of the position starting from the least significant number as 0.

Example 1

Binary: 1011 Decimal: $1 \cdot 2^0 + 1 \cdot 2^1 + 0 \cdot 2^2 + 1 \cdot 2^3 = 1 + 2 + 0 + 8 = 11$

To convert decimal to binary, simply divide the decimal by 2 and takes the remainder. Please note that the result starts from the least significant number.

Example 2

decimal binary
11 ?
11/2 = 5, r:1 1
5/2 = 2, r:1 1
2/2 = 1, r:0 0
1/2 = 0, r: 1 1
11 1011