How to read only half a byte from a binary file at a time in C?

1.2k views Asked by At

Looking at the documentation for fread() in C:

Declaration

Following is the declaration for fread() function.

size_t fread(void*ptr, size_t size, size_t nmemb, FILE *stream)

Parameters

ptr − This is the pointer to a block of memory with a minimum size of size*nmemb bytes.

size − This is the size in bytes of each element to be read.

nmemb − This is the number of elements, each one with a size of size bytes.

stream − This is the pointer to a FILE object that specifies an input stream.

Is there any way to specify the size to be less than a byte? Or a way to move the fptr only a certain number of bits forward?

2

There are 2 answers

1
dbush On

A byte is the smallest unit of data that can be stored or accessed.

You'll need to read a byte, then look at the upper bits and lower bits separately. For example:

unsigned char value = get_value();
unsigned char upper = (value & 0xf0) >> 4;
unsigned char lower = value & 0x0f;
2
0___________ On

you cant, but of course you can write your own fuction.

int readSomeBitsButOnlyLessThan9(FILE *file, size_t bitnum, size_t nbits, unsigned char *result)
{
    long byte = bitnum >> 3;
    int res;
    unsigned short val;

    if(nbits > 8) return -1;

    if(fseek(file, byte, SEEK_SET)) return -1;

    if(((bitnum + nbits) >> 3) > byte) 
    {
        if(fread(&val, 1, 2, file) != 2) return -1;
    }
    else
    {
        if(fread(&val, 1, 2, file) != 2) return -1;
    }
    val >>= 8 - (bitnum & 7);
    *result = val;
    return 0;
}

(It is 1am and I do guarantee that it is error free)