Search code examples
cendianness

How do I write the 4 bytes of an int32_t to a binary file in big-endian order in C?


I want to write the 4 bytes of an int32_t to a binary file in big-endian order. I used fwrite() directly with a pointer to my int32_t, and it somewhat works, but the problem is that my integer is written in little-endian order, with the smallest bytes written first. For example, if I write:

int32_t specialInt = 262;
fwrite(&specialInt, 4, 1, myFile);

and I open it with my hex editor, I see:

06 01 00 00 ...

which is backwards compared to how I want it. I would like:

00 00 01 06 ...

How should I get my int_32t to be in big-endian order? Is there a built-in C library function that will get the bytes in the correct order, or should I use memcpy() to put the bytes into a temp char array, then write the bytes one by one backwards into the file?


Solution

  • Thanks pmg for writing the answer in the comment:

    Assuming CHAR_BIT == 8:

    unsigned char value[4];
    value[0] = (uint32_t)specialInt >> 24;
    value[1] = (uint32_t)specialInt >> 16;
    value[2] = (uint32_t)specialInt >> 8;
    value[3] = (uint32_t)specialInt;
    fwrite(value, 4, 1, myFile);