如何将位存储到巨大的字符数组中以用于文件输入/输出

发布于 2024-09-12 01:43:00 字数 503 浏览 2 评论 0原文

我想将大量信息按位存储到一个块中,并将其保存到文件中。

为了让我的文件不那么大,我想使用少量的位而不是 int 来保存指定的信息。

例如,我想将天、小时、分钟存储到文件中。

我只想要 5 位(天)+ 5 位(小时)+ 6 位(分钟)= 16 位内存用于数据存储。

我找不到一种有效的方法将其存储在块中以放入文件中。

我担心一些大问题:

  1. 我每次要存储的数据长度不是恒定的。这取决于传入的信息。所以我不能用结构体来存储它。

  2. 我的块中不能有任何未使用的位,我搜索了一些主题,提到如果我在 int(4 字节变量)中存储 30 位,那么我保存的下一个 3 位将自动进入下一个 int 。但我不希望它发生!!

  3. 我知道我可以使用右移、左移将数字放入字符中,然后将字符放入块中,但效率很低。

我想要一个 char 数组,我可以继续将指定的位放入其中,并使用 write 将其放入文件中。

I want to store lots of information to a block by bits, and save it into a file.

To keep my file not so big, I want to use a small number of bits to save specified information instead of a int.

For example, I want to store Day, Hour, Minute to a file.

I only want 5 bit(day) + 5 bit(Hour) + 6 bit(Minute) = 16 bit of memory for data storage.

I cannot find a efficient way to store it in a block to put in a file.

There are some big problems in my concern:

  1. the data length I want to store each time is not constant. It depends on the incoming information. So I cannot use a structure to store it.

  2. there must not be any unused bit in my block, I searched for some topics that mentioned that if I store 30 bits in an int(4 byte variable), then the next 3 bit I save will automatically go into the next int. but I do not want it to happen!!

  3. I know I can use shift right, shift left to put a number to a char, and put the char into a block, but it is inefficient.

I want a char array that I can continue putting specified bits into, and use write to put it into a file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初心未许 2024-09-19 01:43:00

我想我只需使用必要的位数来存储任何给定信息可能需要的最大值。然后,霍夫曼在您写入数据时对数据进行编码(显然,霍夫曼在您读取数据时对其进行解码)。大多数其他方法可能效率较低,而且许多方法可能也更复杂。

I think I'd just use the number of bits necessary to store the largest value you might ever need for any given piece of information. Then, Huffman encode the data as you write it (and obviously Huffman decode it as you read it). Most other approaches are likely to be less efficient, and many are likely to be more complex as well.

匿名。 2024-09-19 01:43:00

我还没见过这样的图书馆。所以恐怕你必须自己写一份。无论如何,这不会很困难。

还有关于效率。这种操作总是需要位移位和掩码,因为很少有CPU支持直接对位进行操作,尤其是在两个机器字之间。唯一的区别是您或您的编译器进行翻译。

I haven't seen such a library. So I'm afraid you'll have to write one yourself. It won't be difficult, anyway.

And about the efficiency. This kind of operations always need bits shifting and masking, because few CPUs support directly operating into bits, especially between two machine words. The only difference is you or your compiler does the translation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文