微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 C 语言二进制文件中读取位

如何解决从 C 语言二进制文件中读取位

i have a binary file with data as in the picture

每 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 位,下一位将在我从文件中读取的下一个字节中。

我想过使用面具,但我不确定如何。

有什么想法吗?我该如何解决

谢谢

解决方法

请您尝试以下操作:

#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
,

要从二进制文件中读取二进制数据,我们需要使用这行代码。 `无符号字符缓冲区[10]; 文件 *ptr;

ptr = fopen("test.bin","rb"); // r 为读取,b 为二进制

fread(buffer,sizeof(buffer),1,ptr); // 读取 10 个字节到我们的缓冲区`

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。