【问题标题】:How to convert from bitset back to int如何从 bitset 转换回 int
【发布时间】:2021-03-19 07:24:11
【问题描述】:

所以我目前正在研究文件压缩以便压缩文件,我正在使用霍夫曼编码转换我的整数字符串

示例:

1000011011010100011010100010001101111001001111010011000011011100001010010110011011 1001110011111000010110110101111111

像这样设置位:

int i = 0;
while (i < str.length())
{
    bitset<8>set(str.substr(i, i + 7));
    outputFile << char(set.to_ulong());
    i = i + 8;
}

当我检索该文件的内容时,我不知道如何将其转换回整数字符串。一旦我取回整数字符串,我就可以检索我编码的原始内容,它只是将字符串取回,这就是问题所在

【问题讨论】:

  • 十进制整数字符串?
  • 你知道substr的第二个参数是子串的长度吗?在我看来,您传递的数据比您预期的要多。

标签: c++ file-io huffman-code bitset


【解决方案1】:

如果我正确理解您的问题,您可以执行反向操作:

constexpr int bits_num = sizeof(unsigned char) * CHAR_BIT; //somewhere upper in the file
//...

std::string outputStr;
unsigned char c;
while (inputFile.get(c))  //the simplest function to read "character by character"
{
    std::bitset<bits_num> bset(c);  //initialize bitset with a char value
    outputStr += bset.to_string();  //append to output string
}

当然,我假设您将自己声明和设置inputFile 流。

sizeof(unsigned char) * CHAR_BIT 是一种优雅的方式来表达变量类型中的多个位(例如这里的unsigned char)。要使用常量 CHAR_BIT(在所有现代架构上基本上是 8),请添加 #include &lt;climits&gt; 标头。


您的代码中也有错误:

bitset<8>set(str.substr(i, i + 7));

您每次迭代都会增加剪切子字符串 (i + 7),只需将其更改为 8(或建议的常量更好且不易出错):

constexpr int bits_num = sizeof(unsigned char) * CHAR_BIT;

    //...
    std::bitset<bits_num> set( str.substr(i, bits_num) );
    outputFile << static_cast<unsigned char>( set.to_ulong() );
    i += bits_num;

【讨论】:

  • 这几乎正是我正在寻找的,它部分工作。我编码的原始字符串是 This is the text in my input file ,但现在它显示 t fs is the text in my input fif e 所以出了点问题我只是不知道在哪里
猜你喜欢
  • 2013-11-04
  • 2019-10-24
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 2012-01-08
  • 2012-06-06
  • 2011-05-05
相关资源
最近更新 更多