因为您想枚举所有可能性,您可以简单地使用索引的二进制值。这是一个带有展开循环的版本:
for (i = 0; i < 256; ++i) {
t[i][0] = (i >> 7) & 1;
t[i][1] = (i >> 6) & 1;
t[i][2] = (i >> 5) & 1;
t[i][3] = (i >> 4) & 1;
t[i][4] = (i >> 3) & 1;
t[i][5] = (i >> 2) & 1;
t[i][6] = (i >> 1) & 1;
t[i][7] = (i >> 0) & 1;
}
t 是您的结果数组,i 是循环索引。
t[i][5] = (i >> 2) & 1; 语句(例如)的作用如下:
-
i >> 2 将i 的 3e 位放在 1e 位置;
-
(i >> 2) & 1 让我们知道i 的第 3e 位是 0 还是 1。
示例1:
- 输入:
00001111;
-
i >> 2:00000011;
-
(i >> 2) & 1: 00000001
示例2:
- 输入:
00001011;
-
i >> 2:00000010;
-
(i >> 2) & 1: 00000000
注意我们也可以使用宏来提高可读性:
/* Get the value of the bit at position `n` of `x`. */
#define GET_BIT(x, n) (((x) >> (n)) & 1)
for (i = 0; i < 256; ++i) {
t[i][0] = GET_BIT(i, 7);
t[i][1] = GET_BIT(i, 6);
t[i][2] = GET_BIT(i, 5);
t[i][3] = GET_BIT(i, 4);
t[i][4] = GET_BIT(i, 3);
t[i][5] = GET_BIT(i, 2);
t[i][6] = GET_BIT(i, 1);
t[i][7] = GET_BIT(i, 0);
}
例子:
#include <stdio.h>
/* Get the value of the bit at position `n` of `x`. */
#define GET_BIT(x, n) (((x) >> (n)) & 1)
int main(void)
{
int t[256][8], i, j;
for (i = 0; i < 256; ++i) {
t[i][0] = GET_BIT(i, 7);
t[i][1] = GET_BIT(i, 6);
t[i][2] = GET_BIT(i, 5);
t[i][3] = GET_BIT(i, 4);
t[i][4] = GET_BIT(i, 3);
t[i][5] = GET_BIT(i, 2);
t[i][6] = GET_BIT(i, 1);
t[i][7] = GET_BIT(i, 0);
}
for (i = 0; i < 256; ++i, puts(""))
for (j = 0; j < 8; ++j)
printf("%d", t[i][j]);
return 0;
}