the nth gray code

后端 未结 4 1707
眼角桃花
眼角桃花 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 14:13

    The Wikipedia entry you refer to explains the equation in a very circuitous manner.

    However, it helps to start with this:

    Therefore the coding is stable, in the sense that once a binary number appears in Gn it appears in the same position in all longer lists; so it makes sense to talk about the reflective Gray code value of a number: G(m) = the m-th reflecting Gray code, counting from 0.

    In other words, Gn(m) & 2^n-1 is either Gn-1(m & 2^n-1) or ~Gn-1(m & 2^n-1). For example, G(3) & 1 is either G(1) or ~G(1). Now, we know that Gn(m) & 2^n-1 will be the reflected (bitwise inverse) if m is greater than 2^n-1.

    In other words:

    G(m, bits), k= 2^(bits - 1)
    G(m, bits)= m>=k ? (k | ~G(m & (k - 1), bits - 1)) : G(m, bits - 1)
    G(m, 1) = m
    

    Working out the math in its entirety, you get (m ^ (m >> 1)) for the zero-based Gray code.

提交回复
热议问题