将9位值的流作为字节写入C中的文件 [英] Writing a stream of 9 bit values as bytes to a file in C

查看:283
本文介绍了将9位值的流作为字节写入C中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其整数值为0-511(最多9位)。我试图用 fwrite 将其写入文件。

I have an array with integer values from 0-511 (9 bits max). I am trying to write this to a file with fwrite.

例如,使用数组:

[257, 258, 259]
Which is 100000001, 100000010, 100000011

I am trying to write
100000001100000010100000011 + extra padding of 0s to the file 

但是因为fwrite限制写入一次1个字节,我不知道该怎么做。我是按位操作的新手,而不是如何分离各个字节。

But since fwrite limits writes to 1 byte at a time, I am not sure how to go about doing this. I am new to bitwise operations and am not how to separate out the individual bytes.

推荐答案

你需要一个缓冲区。

由于您当时正在写8位,因此必须
的数据类型至少可以保存9 + 7位。 uint16_t 会这样做,
但是我建议使用至少与原生 int 一样大的大小。请确保使用无符号类型以避免转移问题。

Since you are writing 8 bits at the time, you must have data type that can hold at least 9+7 bits at minimum. uint16_t would do, but I recommend using size that would at least as big as your native int. Make sure you use unsigned types to avoid shifting issues.

uint32_t bitBuffer = 0;  // Our temporary bit storage
uint32_t count = 0;      // Number of bits in buffer

假设我们有单个数据:

uint32_t data9b = 257;  // 1 0000 0001

向缓冲区添加位很简单;只是在缓冲区末尾移位,
并与OR结合。

Adding bits to buffer is simple; just shift bits at the end of the buffer, and combine with OR.

bitBuffer |= (data9b << count); // At first iteration, shift does nothing
count += 9;                     // Update counter

添加9位后,我们可以将8位刷新为文件。

After 9 bits are added, we can flush 8 bits to file.

while(count >= 8) {
    writeToFile(bitBuffer & 0xFF);  // Mask out lowest bits with AND
    bitBuffer >>= 8;                // Remove written bits
    count -= 8;                     // Fix counter
}

每个周期后你剩下0-7位缓冲区。在所有数据结束时,如果您以8位的非倍数结束,只需将 bitBuffer 的剩余内容写入文件。

After each cycle you have 0 - 7 bits left over in the buffer. At the end of all data, if you finish with non-multiple of 8 bits, just write remaining contents of bitBuffer to file.

if(count > 0)
    writeToFile(bitBuffer);

这篇关于将9位值的流作为字节写入C中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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