Skip to main content

Posts

Showing posts from March, 2019

Gray Code

There are many great articles and videos on gray code, why/when we need gray code, how to compute gray code etc..  Here's a comprehensive one: https://en.wikipedia.org/wiki/Gray_code  Among all those articles and videos, this formula is used (^ is logical xor, >> is right shift):  num ^ (num >> 1)  however, I can't find any good explanation about why. I'll try to explain it here in an easy to understand way (not mathematical way). First, we need to understand the easy way of generating sequence of gray code.  You can read the wikipedia page of any other articles out there if you need a very detailed version. Here's my simple version. Let's start with 1 bit, that's easy Decimal Binary Gray 0 0 0 1 1 1 in order to expand to 2 bit, all we need to do is, flip (or mirror) all existing gray code, and prefix 0 to the top half, prefix 1 to the bottom half. so first flip/mirror: Decimal Binary Gray 0 00 0 1 01 1 2 10 1 3 11 0 then p