c - 用 C 语言从二进制文件中读取位
问题描述
每 3 位代表一行或一列。我需要每 3 位读取一次并将它们存储在一个变量中。
到目前为止,这是我的代码:
typedef unsigned char BYTE
void main()
{
FILE* fh = fopen("knightPath.bin", "rb");
checkFileOpening(fh);
BYTE ch ,ch1, ch2;
fread(&ch, sizeof(BYTE), 1, fh);
ch1 = ch >> 5; /* first 3 bits 'C' */
ch2 = ch << 3 >> 5; /* second 3 bits '5' */
fclose(fh);
}
问题是从字母 A 中读取位,因为我在变量 ch 中有 2 位,而下一位将在我从文件中读取的下一个 BYTE 中。
我想过使用面具,但我不知道如何。
有任何想法吗?我怎样才能解决这个问题?
谢谢
解决方案
请您尝试以下方法:
#include <stdio.h>
#include <stdlib.h>
#define FILENAME "knightPath.bin"
int main() {
FILE *fp;
int c, ch1, ch2;
int remain = 0; // remaining buffer (FIFO) size in bit
int buf = 0; // FIFO of bit stream
if (NULL == (fp = fopen(FILENAME, "rb"))) {
fprintf(stderr, "can't open %s\n", FILENAME);
exit(1);
}
while (1) {
if (remain < 6) { // if the FIFO size < 6
c = fgetc(fp); // then read next byte
if (c == EOF) return EXIT_SUCCESS;
remain += 8; // increase the buffer size
buf = (buf << 8) + c; // append the byte to the FIFO
}
ch1 = (buf >> (remain - 3)) & 7;// get the leftmost 3 bits
ch2 = (buf >> (remain - 6)) & 7;// get the next 3 bits
printf("ch1 = %c, ch2 = %d\n", ch1 + 'A', ch2 + 1);
remain -= 6; // decrease the FIFO size
buf &= ((1 << remain) - 1); // clear the processed bits
}
}
输出:
ch1 = C, ch2 = 5
ch1 = A, ch2 = 4
ch1 = B, ch2 = 3
ch1 = D, ch2 = 1
ch1 = E, ch2 = 3
推荐阅读
- python - Python/Flask:有没有办法生成密码提示而不是制作整个用户平台?
- python - Unity POST 到本地主机的请求
- sql - 索引是否会影响 where is not null 查询的性能?
- react-native - undefined 不是对象(评估 '_expo.default.Localization.locale')
- python - IBM 语音转文本用户名和密码问题
- javascript - XMLHttpRequest:如何导航“链接”标头
- spring - 使用 Spring 配置从 Spring 连接到 WebSphere MQ
- python - 无法解决 LinAlgError:数组的最后 2 个维度必须是正方形
- c# - 多个级别的等效名称
- arrays - 文件的读写