您可能会发现此 C 代码很有帮助。
函数 make_sets 生成具有一定权重的所有位模式,因此 main 多次调用它以首先生成具有 1 个设置位的模式,然后是 2 个设置位等。
#include <stdio.h>
#define BYTETOBINARYPATTERN "%d%d%d%d%d"
#define BYTETOBINARY(byte) \
(byte & 0x10 ? 1 : 0), \
(byte & 0x08 ? 1 : 0), \
(byte & 0x04 ? 1 : 0), \
(byte & 0x02 ? 1 : 0), \
(byte & 0x01 ? 1 : 0)
/* Make all bitsets with bits_to_add set bits in the least significant num_bits bits
The most significant bit are taken from high_bits.*/
void make_sets(int high_bits, int bits_to_add, int num_bits) {
// Recurse on the position of the next set bit
int i;
if (bits_to_add) {
for(i=bits_to_add-1;i<num_bits;i++)
make_sets(high_bits + (1<<i), bits_to_add-1, i);
} else {
printf (BYTETOBINARYPATTERN"\n", BYTETOBINARY(high_bits));
}
}
int main(int argc,char *argv[]) {
int M;
for(M=1;M<=5;M++)
make_sets(0,M,5);
}
这将产生输出:
00001
00010
00100
01000
10000
00011
00101
00110
01001
01010
01100
10001
10010
10100
11000
00111
01011
01101
01110
10011
10101
10110
11001
11010
11100
01111
10111
11011
11101
11110
11111