Search code examples
c++iobinarybit-fields

How to Write Bitfield to a Binary File


Lets say I have a bitfield that totals to 32 bits. I want to output these into a binary file, lets call it "binary.bin". How do I go about this without crashing visual studio?

I have found so little information on things like this from previous google searches that I have no idea what to do. The usual response is "no one uses bitfields lmao" but it turns out I need to use bitfields for work.

I understand that bitfields are sometimes under 8 bits, making it impossible to fit onto a byte which makes it hard to do things with, but that doesn't mean I can't take a 32 bit bitfield and put it into a binary file, right?

I found the information on printing to a binary file elsewhere, hopefully it works.

struct bitfield {

    unsigned int     b1 : 22; 
    unsigned int     b2 : 4;
    unsigned int     b3 : 5;
    unsigned int     b4 : 1; 
};
int main(){

    std::ofstream ofile("binary.bin", std::ios::binary);
    ofile.write((char*)&bitfield.b1, sizeof(unsigned int));

    return 0;
}

This doesn't even work and I don't know why, it doesn't like it when i say bitfield.b1

I'd appreciate any help you can throw at me 😘


Solution

  • I notice two problems in your posted code.

    Problem 1.

    You need an object to save its contents to a file, not a type and its member.

    The expression bitfield.b1 is not correct from that standpoint. You need:

    bitfield obj;
    

    After that, you can use obj.b1 to reference the member.

    Problem 2:

    The language does not allow you to get the address of a bit-field member. See Are there any variables whose address can not be obtained?


    Solution

    Create an object and save the entire object to the file, not just a bit field.

    std::ofstream ofile("binary.bin", std::ios::binary);
    bitfield obj;
    ofile.write(retinterpret_cast<char*>(&obj), sizeof(obj));