解码C中的位

时间:2016-10-09 20:06:11

标签: 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));
}

到目前为止,我已经尝试过:

unsigned int byte[CHAR_BIT]; // Filled elsewhere
unsigned char result = 0;
for (int i = 0; i < CHAR_BIT; i++) {
  result |= (byte[i] == '1') << ((CHAR_BIT - 1) - i);
}
putchar(result);

但是输出是错误的,似乎字符的移动量是错误的。假设第一个代码块在一个名为prog1的文件中,第二个代码块在prog2中,那么这个shell命令的输出应该是abc,但它是`bb(字面后退滴答后跟bb)。

echo "abc" | ./prog1 | ./prog2

1 个答案:

答案 0 :(得分:2)

这对我有用:

<强> 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;
}

<强> prog2.c

#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

了解其他地方发生的事情可能有助于解释出现了什么问题。