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

Time:05-13

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?

CodePudding user response:

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);

CodePudding user response:

You could use htonl() function from POSIX 2001 standard available in arpa/inet.h header. See https://linux.die.net/man/3/ntohl

Big endian is Internet byte order, known as "network byte order".

You need to transform int32_t to uint32_t. This cast is defined by C standard. Next transform it to network endian via htonl() and then write it to a file:

int32_t specialInt = 262;
uint32_t encodedInt = htonl((uint32_t) specialInt);
_Static_assert(sizeof encodedInt == 4, "Oops");
fwrite(&encodedInt, 4, 1, myFile);

It could be abbreviated a bit with a compound literal.

fwrite(&(uint32_t) { htonl((uint32_t)specialInt) }, 4, 1, myFile);
  • Related