Search code examples
cbinarybit-manipulationfgets

C how to read in a single bit from a file


I'm reading in a file in binary in C: infile=fopen(input, "rb") and am attempting to read each bit one at a time so if the file contents were:

"hello"

the ascii value of 'h' is 104 so in binary it would be 1101000.

Is there a fgetbit() method which you can call and assign to a primitive type? EX:

int my_bit=fgetbit(infile); //value of my_bit would be 1 for hello example.

Solution

  • You can't get more granular than a byte during file I/O, but if you really want to work at the bit level, you can use a bit mask or a bit shift to isolate the bits you want once you have the bytes read out of the file.

    For example, to output/examine every single bit in a byte:

    #include <limits.h> // for CHAR_BIT
    
    ...
    
    unsigned char b = 0xA5; // replace with whatever you've read out of your file
    for(i = 0; i < CHAR_BIT; i++)
    {
        printf("%d", (b>>i)&1); 
    }
    

    To isolate the most significant bit in a byte:

    unsigned char mask = 0x80; // this value may differ depending on your system's CHAR_BIT
    unsigned char value = /* read from file */;
    if(value & mask)
    {
       // MSB is set
    }
    else
    { 
       // MSB is clear
    }