the nth gray code

后端 未结 4 1704
眼角桃花
眼角桃花 2020-12-09 13:16

the formula for calculating nth gray code is :

(n-1) XOR (floor((n-1)/2))  
(Source: wikipedia)

I encoded it as:

int gray(         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-09 13:52

    Incrementing a number, when you look at it bitwise, flips all trailing ones to zeros and the last zero to one. That's a whole lot of bits flipped, and the purpose of Gray code is to make it exactly one. This transformation makes both numbers (before and after increment) equal on all the bits being flipped, except the highest one.

    Before:

    011...11
         + 1 
    ---------
    100...00
    

    After:

    010...00
         + 1
    ---------
    110...00
    ^<--------This is the only bit that differs 
              (might be flipped in both numbers by carry over from higher position)
    

    n ^ (n >> 1) is easier to compute but it seems that only changing the trailing 011..1 to 010..0 (i.e. zeroing the whole trailing block of 1's except the highest 1) and 10..0 to 11..0 (i.e flipping the highest 0 in the trailing 0's) is enough to obtain a Gray code.

提交回复
热议问题