使用C将整数值写入二进制文件 [英] Writing integer values to a file in binary using C

查看:214
本文介绍了使用C将整数值写入二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将9位数写入二进制文件。

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

例如,我想写整数值:275为 100010011 等等。 fwrite 一次只允许写入一个字节,我不知道如何操作这些位才能做到这一点。

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.

推荐答案

您必须至少写入两个字节来存储9位值。一个简单的解决方案是每9位使用16位值

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

选择16位无符号类型,例如 uint16_t 和存储2个字节

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

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

读取 w 这个词,确保它实际上仅使用其9个第一位(位0~8)

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.

您还可以使用16位字的9位优化该解决方案,然后使用剩余的7位用于存储下一个9位值的前7位等...

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...

参见这个答案解释了如何在C中进行位移。

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

这篇关于使用C将整数值写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆