c - 生成查找表的所有可能的二进制输入

标签 c binary

我必须用 C 代码生成查找表的所有可能输入。我确信它必须递归完成,但我找不到任何方法。你有什么建议吗?谢谢

int main()
{
    int i,j,k;
    int M,N;
    int comb;
    FILE *fp;

    printf("Insert M and N values \n");
    scanf("%d", &M);
    scanf("%d", &N);
    comb = (int) pow(2.0,M);

    int A[comb][M];
    int B[comb][N];

    time_t t;
    srand((unsigned) time(&t));
    fp = fopen("lut.txt","w"); 
    fprintf(fp, "INPUTPINS - %d\n", M);
    fprintf(fp, "OUTPUTPINS - %d\n", N);
    for (i=0; i< comb; i++)
    {
        for(j= 0; j<M; j++)
        {
            fprintf(fp,"%d", A[i][j]);
        }
        fprintf(fp, " - ");
        for (k=0; k<N; k++)
        {
            B[i][k] = rand()%2;
            fprintf(fp, "%d", B[i][k]);
        }
        fprintf(fp,"\n");
    }
    fclose(fp);
    return 0;
}

我需要生成矩阵 A 的值,其中包含所有可能的 2^n 输入,而输出是随机的。

最佳答案

我不明白为什么你需要数组或递归来查找权限。权限是 0 到 2^M - 1 范围内的每个数字。您所需要的只是一个以二进制输出的函数。对 scanf()fopen() 进行一些错误检查会更好。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void pbinary(FILE *fp, int val, int bits)
{
    int mask = 1 << (bits-1);
    while (bits-- > 0) {
        fprintf (fp, "%d", (val & mask) != 0);
        mask >>= 1;
    }
}

int main()
{
    int i, M, N, comb;
    FILE *fp;
    printf("Insert M and N values \n");
    scanf("%d", &M);
    scanf("%d", &N);
    comb = 1 << M;

    srand((unsigned)time(NULL));
    fp = fopen("lut.txt","w"); 
    fprintf(fp, "INPUTPINS - %d\n", M);
    fprintf(fp, "OUTPUTPINS - %d\n", N);
    for (i=0; i< comb; i++)
    {
        pbinary (fp, i, M);
        fprintf(fp, " - ");
        pbinary (fp, rand(), N);
        fprintf(fp,"\n");
    }
    fclose(fp);
    return 0;
}

程序输入

Insert M and N values
3
4

文件输出

INPUTPINS - 3
OUTPUTPINS - 4
000 - 1001
001 - 0101
010 - 0110
011 - 0100
100 - 1001
101 - 0011
110 - 0111
111 - 1111

关于c - 生成查找表的所有可能的二进制输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28693742/

相关文章:

c - C 中 int 数组的初始值 - 为什么?

android - 使用 javah 工具时包含 Android 平台 jar

c - 将逗号分隔的多个整数分配给 C 中的一个 int - 为什么这样做有效?做什么的?

MySQL 在将十六进制转换为二进制时去除前导零

java - 如何将 java BigDecimal 转换为普通字节数组(不是 2 的补码)

Java - 从 BIN 文件读取数组或将数组写入 BIN 文件

c - 为什么此代码打印 "False",尽管 int 的大小大于 -1?

c - 没有正确完成 if 语句

c# - 将逗号分隔的二进制字符串转换为 byte[] 以插入注册表

c - 使用 XOR 交换单个位