Circuit Shorts: Binary to Gray Code
on
Some Gray codes, those that are ‘cyclic’, have the added benefit that when they ‘roll’ — go from the ‘terminal count’ to the initial state — there is also only one bit change (that is, the first and last number are different by a single bit change). The Wikipedia page for Gray code is fascinating and worth a read. In this page, I found code for converting binary code to Gray. Something like this:
num_gray = num_bin ^ (num_bin >> 1)
Where ^ is XOR and >> is ‘shift right by one.’ Pretty neat, and easy to remember for the next time you’re asked at a party for the Gray of 10010110. You could quickly answer 11011101 after consulting a napkin scribble. Huge applause to you!
I’ve wondered what the logic circuit may look like. I wasn’t clever enough to directly convert the code above to gates so I looked at the bits.

We see that in the case of a single bit — in yellow — the binary and Gray are the same. In hardware, that’s just a wire. For two bits — in blue — we see that the most significant bit (MSB) is G1 = B1, and the least significant bit (LSB) is G0 = NOT B0. Looking at three bits — in purple — G2 = B2 as before, but the negation rule no longer works. We need a new strategy. Looking for more elaborate patterns we may notice that Gn = Bn XOR Bn+1 for GN-1 to G0 and GN = BN!
I may have taken the naive approach to solving this problem. How would you do it better or differently?
More on Circuit Design, Gray Code, and More
Interested in circuit design and related topics?- Articles about Circuit Design, ElektorMagazine.com.
- S. Drimer, "Circuit Shorts: The Flavors of Binary-Coded Decimals (BCD)," March 18, 2021.
- Subscribe to the "Circuit Shorts" tag for updates when new articles are published.
Need a rapid prototyping solution? Check out ElektorPCB4Makers. You can get two PCB prototypes in three working days!


Discussion (4 comments)