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

Laravel Slow queries

5  Asked on November 7, 2021 by squiggs


Display image that returns HTTP 503 in Firefox

2  Asked on November 7, 2021 by brainstone


Simple TCP listener on swift

1  Asked on November 7, 2021 by mr-park


check the type of the only child in react

1  Asked on November 7, 2021


Cannot update document using the NodeJS MongoDB driver

1  Asked on November 7, 2021 by niaz-m-sameer


Can not convert umlauts (Ü Ö Ä ü ö ä è é) to .utf8

2  Asked on November 7, 2021 by salome-tsiramua


elegant way of extracting option value when need it

1  Asked on November 7, 2021 by user804968


Sign PDF asynchronous using PDFBox

0  Asked on November 7, 2021 by lawrence-leung


Get non hidden element with previousElementSibling

2  Asked on November 7, 2021 by jens-trnell


Ask a Question

Get help from others!

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