Deriving nth Gray code from the (n-1)th Gray Code

前端 未结 2 1145
悲&欢浪女
悲&欢浪女 2021-01-07 13:32

Is there a way to derive the 4-bit nth Gray code using the (n-1)th Gray code by using bit operations on the (n-1)th Gray Code?

For example the 4th Gray code is 0010.

相关标签:
2条回答
  • 2021-01-07 13:57

    Perhaps it's "cheating" but you can just pack a lookup table into a 64-bit constant value, like this:

    0000 0 -> 1
    0001 1 -> 3
    0011 3 -> 2
    0010 2 -> 6
    0110 6 -> 7
    0111 7 -> 5
    0101 5 -> 4
    0100 4 -> C
    1100 C -> D
    1101 D -> F
    1111 F -> E
    1110 E -> A
    1010 A -> B
    1011 B -> 9
    1001 9 -> 8
    1000 8 -> 0
    
    FEDCBA9876543210 nybble order (current Gray code)
    |              |
    V              V
    EAFD9B80574C2631 next Gray code
    

    Then you can use shifts and masks to perform a lookup (depending on your language):

    int next_gray_code(int code)
    {
         return (0xEAFD9B80574C2631ULL >> (code << 2)) & 15;
    }
    

    Alternatively, you can use the formula for converting from Gray to binary, increment the value, and then convert from binary to Gray, which is just n xor (n / 2):

    int next_gray_code(int code)
    {
        code = code ^ (code >> 2);
        code = code ^ (code >> 1);
        code = (code + 1) & 15;
        return code ^ (code >> 1);
    }
    
    0 讨论(0)
  • 2021-01-07 14:03

    What about the following?

    t1 := XOR(g0, g1)
    b0 := !XOR(g0, g1, g2, g3)
    b1 := t1 & g2 & g3 + !t1 & !g2 & !g3
    b2 := t1 & g2 & !g3
    b3 := t1 & !g2 & !g3
    
    n0 := XOR(b0, g0)
    n1 := XOR(b1, g1)
    n2 := XOR(b2, g2)
    n3 := XOR(b3, g3)
    

    The current gray code word is g3 g2 g1 g0 and the next code word is n3 n2 n1 n0. b3 b2 b1 b0 are the four bits which flip or not flip a bit in the code word to progress to the subsequent code word. Only one bit is changed between adjacent code words.

    0 讨论(0)
提交回复
热议问题