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

Stack Overflow Asked by nguyenvivian on October 9, 2020

Looking at the documentation for fread() in C:


Following is the declaration for fread() function.

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


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 Answers

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

Answered by P__J__ on October 9, 2020

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;

Answered by dbush on October 9, 2020

Add your own answers!

Related Questions

Undefined reference to vtable

19  Asked on November 20, 2021 by ryang


Using wildcards in between a C# DataTable Select statement

3  Asked on November 20, 2021 by bugaboo


SendKeys.send is sending more than one character

1  Asked on November 20, 2021 by onur-klekci


pwsh -Command is removing quotation marks

3  Asked on November 20, 2021 by chris-g


Django when is concrete inheritance appropriate

1  Asked on November 20, 2021 by natehawkboss


Get the sum of numbers from array objects

6  Asked on November 20, 2021 by askmen


Function to keep listening a service Angular 8

2  Asked on November 20, 2021 by rob-none


How to perform mathematical operation which is stored as character in R?

1  Asked on November 20, 2021 by hidden-layer


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP