如何从 bitset 转换回 int
How to convert from bitset back to int
所以我目前正在进行文件压缩,以便压缩我正在使用霍夫曼编码转换我的整数字符串的文件
示例:
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;
}
当我检索该文件的内容时,我不知道如何将它转换回整数字符串。一旦我取回整数字符串,我就可以检索我编码的原始内容,只是取回字符串,这就是问题所在
如果我正确理解你的问题,你可以执行反向操作:
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 <climits>
header.
您的代码也有错误:
bitset<8>set(str.substr(i, i + 7));
您在每次迭代 (i + 7
) 中增加切出的子字符串,只需将其更改为 8
(或更好地减少 error-prone 到建议的常量):
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;
所以我目前正在进行文件压缩,以便压缩我正在使用霍夫曼编码转换我的整数字符串的文件
示例:
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;
}
当我检索该文件的内容时,我不知道如何将它转换回整数字符串。一旦我取回整数字符串,我就可以检索我编码的原始内容,只是取回字符串,这就是问题所在
如果我正确理解你的问题,你可以执行反向操作:
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 <climits>
header.
您的代码也有错误:
bitset<8>set(str.substr(i, i + 7));
您在每次迭代 (i + 7
) 中增加切出的子字符串,只需将其更改为 8
(或更好地减少 error-prone 到建议的常量):
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;