Writing integer values to a file in binary using C

2019-08-06 02:49发布

问题:

I am trying to write 9 bit numbers to a binary file.

For example, i want to write the integer value: 275 as 100010011 and so on. fwrite only allows one byte to be written at a time and I am not sure how to manipulate the bits to be able to do this.

回答1:

You have to write a minimum of two bytes to store a 9-bits value. An easy solution is to use 16 bits per 9 bits value

Choose a 16 bits unsigned type, eg uint16_t and store the 2 bytes

 uint16_t w = 275;
 fwrite(&w, 1, 2, myfilep);

Reading the word w, ensure it actually uses only its 9 first bits (bits 0~8)

 w &= 0x1FF;

Note that you might have endianness issues if you read the file on another system that doesn't have the same endianness as the system that wrote the word.

You could also optimize that solution using 9 bits of a 16 bits word, then using the remaining 7 bits to store the first 7 bits of the next 9 bits value etc...

See this answer that explains how to work with bit shifting in C.