Writing integer values to a file in binary using C

烈酒焚心 提交于 2019-12-14 02:27:15

问题


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.



来源:https://stackoverflow.com/questions/47504816/writing-integer-values-to-a-file-in-binary-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!