fangio fangio - 1 year ago 58
C Question

C - Writing integers to binary file using only 3 bytes

I have a programm in C that writes a frequency table to a binary file.
The frequency table is an array filled with structs that contains an int and a char.

So I have to write an unsigned int counter and an unsigned char character to the file (multiple times).

I know that an integer normally uses 4 bytes however I know that the int counter can never be bigger than 2^24-1.

So I could use 4 bytes to write the counter and the character to the file => 3 bytes for counter and 1 byte for the character. This would also be easy to read.

Is there an easy way to do this in C without using special libraries?

Answer Source

Yes, there is a very easy way of doing it in C. You can combine a char, which is one byte on all platforms, with an int of up to 24 bits in size by shifting the char by 24 bits to the left:

uint32_t toWrite = (myChar << 24) | myCount;

When you read the data back, perform the opposite operation:

uint32_t fromFile;
uint32_t myCount = fromFile & 0xFFFFFF;
char myChar = (fromFile >> 24) & 0xFF;