Search code examples
cuint32uint32-t

Encode and combine int to 32bit int in C binary file


Lets say I have 2 variables:

int var1 = 1; //1 byte
int var2 = 2; //1 byte

I want to combine these and encode as a 32bit unsigned integer (uint32_t). By combining them, it would be 2 bytes. I'd then fill the remaining space with 2 bytes of 0 padding. This is to write to a file, hence the need for this specific type of encoding.

So by combining the above example variables, the output I need is:

1200 //4 bytes

Solution

  • There's no need to go the roundabout way of "combining" the values into an uint32_t. Binary files are streams of bytes, so writing single bytes is very possible:

    FILE * const out = fopen("myfile.bin", "wb");
    const int val1 = 1;
    const int val2 = 2;
    if(out != NULL)
    {
      fputc(val1, out);
      fputc(val2, out);
      // Pad the file to four bytes, as originally requested. Not needed, though.
      fputc(0, out);
      fputc(0, out);
      fclose(out);
    }
    

    This uses fputc() to write single bytes to the file. It takes an integer argument for the value to write, but treats it as unsigned char internally, which is essentially "a byte".

    Reading back would be just as simple, using e.g. fgetc() to read out the two values, and of course checking for failure. You should check these writes too, I omitted it because error handling.