Search code examples
qtbinaryfiles

Read n bits (not bytes) in qt?


I'm very newbie in Qt. I have to read a binary file which contains a header. But in some positions I have to read 15 bits and 17 bits integers. Is there any functions to read n bits from a file in qt? PS: I read this file using Matlab by using fread and ubitn


Solution

  • You can only read, and generally handle values in a minimum of 8 bits which is a char or 1 byte.

    You can perform operations on single bit within a byte.

    In your situation, you should read the sufficient amount of byte and then recast to a structure for instance.

    Bitfield

    struct {
       unsigned double widthValidated : 15;
       unsigned double heightValidated : 17;
    } MyStruct;
    
    MyStruct * ptr = (MyStruct *) &myDouble;
    

    You can also use bit shifting:

    double myValue;
    double a = myValue & 0x7FFF; // 15 first bits
    double b = (myValue >> 15) & 0x7FFFF; // 17 bits after the 15 first