1

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.

user100663
  • 47
  • 5
  • See also [Writing a stream of 9-bit values as bytes to a file in C](https://stackoverflow.com/questions/47505922/writing-a-stream-of-9-bit-values-as-bytes-to-a-file-in-c) — a successor question by the same OP also about 9-bit values. – Jonathan Leffler Nov 27 '17 at 07:56

1 Answers1

0

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.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100