为什么位为 01110011 的字节没有变成字符 s?

why does the byte with bits 01110011 not become the character `s`?

为什么下面的程序不打印 s 个字符?:

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


int main(void) {
    unsigned char s = '[=10=]';
    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;
}

所以我基本上是在尝试从位列表中创建 s 字符。 为什么我从这个程序中得到一些其他奇怪的字符?

您插入的位的顺序与它们在源中列出的顺序相反。第二位将移动 1,而不是 6,依此类推。所以得到的数字是

1 1 0 0 1 1 1 0

这是 0xce,十进制 206,因此是非 ASCII。

此外,使用 XOR 来执行此操作非常奇怪,它应该只是规则的按位或 (|)。

这是一个固定的尝试:

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);

这会打印 s.

二进制数以相反的顺序存储在 char 变量 s 中,这就是您遇到此问题的原因。

0 1 1 1 0 0 1 1

它正在成为

1 1 0 0 1 1 1 0

在 's' 变量中。