将位数据输出到二进制文件C++; 我编写压缩程序,需要用C++编写二进制数据到二进制文件。如果有人能就书面声明或网站提供建议,我将不胜感激
抱歉,如果这是一个简单或令人困惑的问题,我正努力在网上找到答案。将位收集成整字节,例如无符号字符或std::位集(其中位集大小是字符位的倍数),然后一次写入整字节。计算机“处理位”,但可用的抽象——特别是IO——是作为程序员处理单个字节。按位操作可用于切换特定位,但您总是处理字节大小的对象 在输出结束时,如果没有完整的字节,则需要决定如何存储该字节。iostreams和stdio都可以分别使用ostream::write和fwrite写入未格式化的数据将位数据输出到二进制文件C++; 我编写压缩程序,需要用C++编写二进制数据到二进制文件。如果有人能就书面声明或网站提供建议,我将不胜感激,c++,bit-manipulation,huffman-code,C++,Bit Manipulation,Huffman Code,抱歉,如果这是一个简单或令人困惑的问题,我正努力在网上找到答案。将位收集成整字节,例如无符号字符或std::位集(其中位集大小是字符位的倍数),然后一次写入整字节。计算机“处理位”,但可用的抽象——特别是IO——是作为程序员处理单个字节。按位操作可用于切换特定位,但您总是处理字节大小的对象 在输出结束时,如果没有完整的字节,则需要决定如何存储该字节。iostreams和stdio都可以分别使用ostream::write和fwrite写入未格式化的数据 P>而不是单个字符或比特集(8是CHAR
<> P>而不是单个字符或比特集(8是CHARYBIT最常用的值),您可以考虑使用更大的块大小,例如4-32或更多的数组、字符或等效大小的位集。我发现最有用的技巧是将所有二进制文件作为单个数组存储在内存中,然后将其全部移动到硬盘上。一次执行一位,一次执行一个字节,或者一次执行一个无符号long-long,都不如将所有数据存储在一个数组中并使用“fwrite()”的一个实例将其存储到硬盘驱动器 大小写入(const void*ptr、大小、大小计数、文件*流) 参考: 英文: fwrite([存储数据的数组*),[数组对象的字节大小。对于无符号字符->1,对于无符号长长度->8],[数组中的实例数],[文件*]) 始终检查您的报税表以确认是否成功 此外,还可以提出一个论点,即让对象类型尽可能大是最快的方法([unsigned long]>[char])。虽然我对“fwrite()”背后的编码并不精通,但我觉得从代码中使用的自然对象转换为[unsigned long long]所需的时间要比“fwrite()”所需的时间还要长
当我学习哈夫曼编码时,我花了几个小时才意识到[char]和[unsigned char]之间有区别。注意,对于这种方法,您应该始终使用无符号变量来存储纯二进制。通过下面的类,您可以逐位写入和读取
class bitChar{
public:
unsigned char* c;
int shift_count;
string BITS;
bitChar()
{
shift_count = 0;
c = (unsigned char*)calloc(1, sizeof(char));
}
string readByBits(ifstream& inf)
{
string s ="";
char buffer[1];
while (inf.read (buffer, 1))
{
s += getBits(*buffer);
}
return s;
}
void setBITS(string X)
{
BITS = X;
}
int insertBits(ofstream& outf)
{
int total = 0;
while(BITS.length())
{
if(BITS[0] == '1')
*c |= 1;
*c <<= 1;
++shift_count;
++total;
BITS.erase(0, 1);
if(shift_count == 7 )
{
if(BITS.size()>0)
{
if(BITS[0] == '1')
*c |= 1;
++total;
BITS.erase(0, 1);
}
writeBits(outf);
shift_count = 0;
free(c);
c = (unsigned char*)calloc(1, sizeof(char));
}
}
if(shift_count > 0)
{
*c <<= (7 - shift_count);
writeBits(outf);
free(c);
c = (unsigned char*)calloc(1, sizeof(char));
}
outf.close();
return total;
}
string getBits(unsigned char X)
{
stringstream itoa;
for(unsigned s = 7; s > 0 ; s--)
{
itoa << ((X >> s) & 1);
}
itoa << (X&1) ;
return itoa.str();
}
void writeBits(ofstream& outf)
{
outf << *c;
}
~bitChar()
{
if(c)
free(c);
}
};
谢谢你的建议,弗雷德,这让我知道该去哪里找。
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
ofstream outf("Sample.dat");
ifstream inf("Sample.dat");
string enCoded = "101000001010101010";
//write to file
cout << enCoded << endl ; //print 101000001010101010
bitChar bchar;
bchar.setBITS(enCoded);
bchar.insertBits(outf);
//read from file
string decoded =bchar.readByBits(inf);
cout << decoded << endl ; //print 101000001010101010000000
return 0;
}