简体   繁体   English

我可以在C ++中输入/输出位吗

[英]Can I input/output bits in C++

I am figuring out how to compress files and I was wondering if I could do bit manipulation with an output file. 我在想如何压缩文件,我想知道是否可以对输出文件进行位操作。

Current I have a string of variable size n that contains only 0's and 1's. 当前,我有一个可变大小n的字符串,仅包含0和1。 ex: 010111001010110 例如:010111001010110

I want to output a file that contains only n bits instead of n characters. 我想输出一个仅包含n位而不是n个字符的文件。

Also, if that is possible, how can I read those bits back and convert it back into a string? 另外,如果可能的话,我该如何读回这些位并将其转换回字符串?

Thank you. 谢谢。

Update: If I cannot write out bits directly and have to pack it into bytes, does that mean I can convert the 8 bits into a char and just output a list of char? 更新:如果我无法直接写出位并将其打包为字节,这是否意味着我可以将8位转换为char并仅输出char列表? If so, what happens if I try to store "00000000", which means null? 如果是这样,如果我尝试存储“ 00000000”(意味着为空)会怎样?

You can't write bits out directly, you have to pack them at least in eights. 您不能直接写出位,必须至少将它们打包成八位。 Yes, that means writing out bytes. 是的,这意味着要写出字节。 Note that the output will be essentially padded to bytes and you have to do something about it. 请注意,输出实际上将被填充为字节,您必须对此做一些事情。

To convert a string containing 0s and 1s to a raw data, the easiest way is to either use std::bitset , if you know the length, or write a loop that advances by eights, as in 要将包含0和1的字符串转换为原始数据,最简单的方法是使用std::bitset (如果您知道长度),或者编写一个前进八分的循环,例如

for (auto i = 0; i < str.size(); i += 8)

If you look the net for arb255.zip you will find my bijective arithmetic coder. 如果您在网上寻找arb255.zip,您会发现我的双射算术编码器。 The io used for program is BIT I/O of course the files are really in bytes. 用于程序的io是BIT I / O,当然文件的确以字节为单位。 But the strings are bijective to the byte file. 但是字符串对字节文件是双射的。 Its all handled in the includes but its true bijective bit IO as far as the main routines see. 它的所有内容都包含在其中,但就主例程而言,其真正的双射位IO。

Actually the old code for DJPP GNU C is at bijective.dogma.net some changes are needed to work in current C but the I/O should still work 实际上,DJPP GNU C的旧代码是在bijective.dogma.net上,需要一些更改才能在当前C中工作,但I / O仍然可以工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM