1
votes

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?

2
What does it print? How about trying to print it in hex so you can see what happened? - Andrew Henle
@AndrewHenle it prints this character: "Î" - Sebastian Karlsson
î is not ascii so the value are probably not stored well - maf88

2 Answers

8
votes

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.

0
votes

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.