[英]Decode bits in C
我正在尝试通过以下循环解码已编码的二进制文件(最高有效字节在前)。
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
这对我有用:
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
并且知道发生在其他地方的事情可能有助于解释问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.