Search code examples
cfilebinarybit

reading bits from a binary file in C language


i have a binary file with data as in the picture

every 3 bits represent a row or a col. i need to read every 3 bits and store them in a variable.

this is my code so far:

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

The problem is reading the bits from the letter A because i have 2 bits of it in the variable ch and the next bit will be in the next BYTE i read from the file.

i thought about using mask but i am not sure how.

any ideas? how can i work this out?

thanks


Solution

  • Would you please try the following:

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

    Output:

    ch1 = C, ch2 = 5
    ch1 = A, ch2 = 4
    ch1 = B, ch2 = 3
    ch1 = D, ch2 = 1
    ch1 = E, ch2 = 3