1

Why does the following program not print an s character?:

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


int main(void) {
    unsigned char s = '\0';
    unsigned int bits[8] = {0, 1, 1, 1, 0, 0, 1, 1};

    for (int i = 0; i < 8; i++) {
        s ^= bits[i] << i;
    }

    printf("%c\n", s);

    return 0;
}

So I am basically trying to create the s character from a list of bits. Why do I get some other weird character from this program?

Sebastian Karlsson
  • 715
  • 1
  • 8
  • 19

2 Answers2

8

You are inserting the bits in the inverse order from the one they're listed in the source. The second bit will be shifted by 1, not 6 and so on. So the resulting number is

1 1 0 0 1 1 1 0

which is 0xce, decimal 206 and therefore non-ASCII.

Also, using XOR to do this is very weird, it should just regular bitwise OR (|).

Here's a fixed attempt:

char s = 0;
const unsigned char bits[] = { 0, 1, 1, 1, 0, 0, 1, 1 };

for (int i = 0; i < 8; ++i) {
    s |= bits[i] << (7 - i);
}
printf("%c\n", s);

This prints s.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

The binary number is storing in reverse order in the char variable s that's why you are having this problem.

0 1 1 1 0 0 1 1

it is becoming

1 1 0 0 1 1 1 0

in the 's' variable.

Kousik
  • 465
  • 3
  • 15