Noc
Noc

Reputation: 519

Generating Binary Inputs in C

Essentially, I have a program that has eight variables. I'm attempting to check every combination of truth values for these eight variables, and so I need a truth table using 0s and 1s that demonstrate every combination of them. These inputs will be read into the program.

It should look something like:

0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0
0 0 0 0 0 0 1 1

And so on...

How would I accomplish this in C? I've opened up a file for writing, but I'm not sure how to... Logically do this.

Upvotes: 0

Views: 86

Answers (2)

user529758
user529758

Reputation:

Two loops and the character '0' are more than enough...

FILE *f = fopen("truth.txt", "w"); // we'll alter the truth...
assert(f != NULL);

unsigned i;
int j;
for (i = 0; i < 256; i++) {
    for (j = 0; j < 8; j++) {
        fprintf(f, "%c ", '0' + ((i >> (7 - j)) & 1));
    }
    fprintf(f, "\n");
}

fclose(f);

Upvotes: 1

Bharat Gaikwad
Bharat Gaikwad

Reputation: 530

Convert every decimal number till 2^8, into corresponding binary number... and you have the required pattern.....

Upvotes: 1

Related Questions