用C语言解码位

用C语言解码位,c,binary,bit-manipulation,C,Binary,Bit Manipulation,我正在尝试用下面的循环对编码的二进制文件进行解码(首先是最高有效字节) int ch; // Has a value of, for example, 97 (which evaluates to 'a' with putchar(ch)) for (int i = 0; i < CHAR_BIT; i++) { printf("%d", !!((ch << i) & 0x80)); } 这对我很有用: prog1.c #include <stdio.h&g

我正在尝试用下面的循环对编码的二进制文件进行解码(首先是最高有效字节)

int ch; // Has a value of, for example, 97 (which evaluates to 'a' with putchar(ch))
for (int i = 0; i < CHAR_BIT; i++) {
  printf("%d", !!((ch << i) & 0x80));
}
这对我很有用:

prog1.c

#include <stdio.h>

#define CHAR_BIT 8

void encode(int c) {
    for (int i = 0; i < CHAR_BIT; i++) {
        printf("%d", !!((c << i) & 0x80));
    }
}

int main() {
    int c;

    while ((c = getchar()) != EOF) {
        encode(c);
    }

    printf("\n");

    return 0;
}
#include <stdio.h>
#include <string.h>

#define CHAR_BIT 8

void decode(char *byte) {
    int c = 0;

    for (int i = 0; i < CHAR_BIT; i++) {
        c |= (byte[i] == '1') << ((CHAR_BIT - 1) - i);
    }

    putchar(c);
}

int main() {
    char byte[CHAR_BIT + 1];

    while (scanf("%8s", byte) == 1) {
        decode(byte);
    }

    return 0;
}
如果编码/解码逻辑与您的相同,则此行可疑:

unsigned int byte[CHAR_BIT]; // Filled elsewhere

知道其他地方发生了什么可能有助于解释错误。

当你说“输出错误”时,你能指定输入/输出是什么以及你期望的是什么吗?你写的ch是一个int。它不应该是一个char吗?在赋值结果时,你将操作数与int类型(由于整数提升)和char类型混合。尤其是使用OR(|)运算符,这可能是个坏主意…@Lundin我想你忽略了这样一个事实,即他编写了两个单独的二进制文件,它们通过管道相互连接,只是一条注释,如果不明显,最后八位“00001010”是新行的编码,如“abc\n”中所示。
#include <stdio.h>
#include <string.h>

#define CHAR_BIT 8

void decode(char *byte) {
    int c = 0;

    for (int i = 0; i < CHAR_BIT; i++) {
        c |= (byte[i] == '1') << ((CHAR_BIT - 1) - i);
    }

    putchar(c);
}

int main() {
    char byte[CHAR_BIT + 1];

    while (scanf("%8s", byte) == 1) {
        decode(byte);
    }

    return 0;
}
> echo "abc" | ./prog1 
01100001011000100110001100001010
> echo "abc" | ./prog1 | ./prog2
abc
> 
unsigned int byte[CHAR_BIT]; // Filled elsewhere