algorithm behind the generation of the reverse bits lookup table(8 bit)

后端 未结 3 462
余生分开走
余生分开走 2021-02-04 13:17

I found the lookup table here. The table is generated as a reverse bits table of 8 bits.

I can not figure out why it works. Please explain the theory behind it. Thanks<

3条回答
  •  太阳男子
    2021-02-04 13:54

    Reverse bits table is just one of possible offline generated constants. People find an algorithm to define it by using unrolling macro. It won't be possible to find such algorithm for another constant. So you will have to maintain some generators infrastructure anyway.

    #include 
    #include 
    #include 
    #include 
    
    #define BYTES_PER_LINE 16
    #define BYTES_GLUE ", "
    #define LINE_PREFIX "  "
    #define LINE_TERMINATOR ",\n"
    
    #define PRINT(string) fwrite(string, 1, sizeof(string), stdout)
    
    static inline void print_reversed_byte(uint8_t byte) {
      uint8_t reversed_byte = 0;
    
      for (uint8_t bit_index = 0; bit_index < 8; bit_index++) {
        uint8_t bit_value = (byte >> bit_index) & 1;
        reversed_byte |= bit_value << (7 - bit_index);
      }
    
      printf("0x%02x", reversed_byte);
    }
    
    int main() {
      uint8_t index = 0;
    
      while (true) {
        if (index != 0) {
          if (index % BYTES_PER_LINE == 0) {
            PRINT(LINE_TERMINATOR);
            PRINT(LINE_PREFIX);
          } else {
            PRINT(BYTES_GLUE);
          }
        }
    
        print_reversed_byte(index);
    
        if (index == 255) {
          break;
        }
        index++;
      }
    
      return 0;
    }
    

    Use it in generated_constants.c.in with cmake:

    const uint8_t REVERSE_BITS_TABLE[256] = {
      @CMAKE_REVERSE_BITS_TABLE@
    };
    

    You will receive pretty and compact table.

    See it's usage in LZWS for example.

提交回复
热议问题