繁体   English   中英

将位写入C ++文件

[英]writing bits into a c++ file

我正在进行霍夫曼编码,并且已经用

std::map<char,int> frequencyTable;

然后,我构建了霍夫曼树,然后以这种方式构建了代码表:

std::map<char,std::vector<bool> > codes;

现在,我将逐字符读取输入文件,并通过代码表对它们进行编码,但是我不知道如何将位写入二进制输出文件。 有什么建议吗?

更新:现在我正在尝试这些功能:

void Encoder::makeFile()
{
char c,ch;
unsigned char ch2;
while(inFile.get(c))
{
    ch=c;
    //send the Huffman string to output file bit by bit
    for(unsigned int i=0;i < codes[ch].size();++i)
    {
        if(codes[ch].at(i)==false){
            ch2=0;
        }else{
            ch2=1;
        }
        encode(ch2, outFile);
    }
}
ch2=2; // send EOF
encode(ch2, outFile);

inFile.close();
outFile.close();
}

和这个:

void Encoder::encode(unsigned char i, std::ofstream & outFile)
{
int bit_pos=0; //0 to 7 (left to right) on the byte block
unsigned char c; //byte block to write

if(i<2) //if not EOF
{
    if(i==1)
        c |= (i<<(7-bit_pos)); //add a 1 to the byte
    else //i==0
        c=c & static_cast<unsigned char>(255-(1<<(7-bit_pos))); //add a 0
    ++bit_pos;
    bit_pos%=8;
    if(bit_pos==0)
    {
        outFile.put(c);
        c='\0';
    }
}
else
{
    outFile.put(c);
}
}

但是,我不知道为什么,它不起作用,循环永远不会执行,编码功能也永远不会使用,为什么?

您不能直接将单个位写入文件。 读/写的I / O单位是一个字节(8位)。 因此,您需要将bool打包成8位的块,然后写入字节。 例如,请参阅以位形式将文件 写入 C中的文件如何将单个位写入C中的文件

C ++标准流支持访问底层CPU支持的最小单元。 那是一个字节。

在C ++中有一个像Stanford Bitstream Class这样的位流类实现。

另一种方法可以使用std :: bitset类。

暂无
暂无

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

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