C编译时查找table代

C compile-time lookup table generation

this answer about brute-forcing 2048 AI, a lookup table storing "2048 array shifts" is precomputed to save needless repetitive calculation. In C, to compute this lookup table at compile time, the way I know of is the "caveman-simple solution" 中,table 本身作为另一个文件生成,然后是 #included,类似这样的 python 脚本生成 lut.include (替换为 2048 特定代码):

#!/usr/bin/python

def swapbits(x):
    ret=0
    for i in range(8):
        if x&(1<<i): ret |= 1<<(7-i)
    return ret

print "const uint8_t bitswap[] = {",
print ", ".join("0x%02x"%swapbits(x) for x in range(256)),
print "}"

有没有更简洁的方法?也就是说,也许一些预处理器技巧可以生成这些 tables?使用 C++ 这应该可以使用 constexpr.

C 预处理器没有循环。您必须在 C 预处理器中写入所有数字,一种方式或另一种方式。

Cleaner meaning does not involve another script and included file

首先,实现一个常量表达式交换位:

#define SWAPBITS(x)  ((x&1)<<7)|((x&2)<<6)|((x&3)<<5).... etc.

然后你只需要写下所有的数字:

const uint8_t arr[] = 
   SWAPBITS(0),
   SWAPBITS(1),
   ... etc. ...
   // Because you do not want to use external script, write all the numbers manually here.
};

如果可以解除“包含文件”,可以使用BOOST_PP_REPEAT。注意那个宏literally lists all iterations it can be called with。类似于 p99 库中的 P99_REPEAT

#include <boost/preprocessor/repetition/repeat.hpp>
#define SWAPBITS(x)  .. as above ..
#define SWAPBITS_DECL(z, n, t)  SWAPBITS(n),
const uint8_t arr[] = {
   BOOST_PP_REPEAT(256, SWAPBITS_DECL,)
};