gpt4 book ai didi

c++ - 字符串转为二进制

转载 作者:行者123 更新时间:2023-12-02 01:50:39 25 4
gpt4 key购买 nike

我使用我们编写的霍夫曼编码来压缩文件。该函数采用 String ,其输出为 String

问题是我想将它保存为二进制文件以获得比原始大小更小的大小,但是当我将它作为字符串取回(0和1)时,它的大小比主文件大。如何将该字符串(0 和 1)转换为二进制,以便每个字符都保存在 1 位中?我正在使用 Qt 来实现这一点:

string Huffman_encoding(string text)
{
buildHuffmanTree(text);

string encoded = "";
unordered_map<char, string> StringEncoded;
encoding(main_root, "", StringEncoded);

for (char ch : text) {
encoded += StringEncoded[ch];
}
return encoded;
}

最佳答案

规范的解决方案使用接受位串并发出打包字节的“位打包器”。首先,将 encoded 替换为以下实例:

class BitPacker {
QByteArray res;
quint8 bitsLeft = 8;
quint8 buf = 0;

public:
void operator+=(const std::string& s) {
for (auto c : s) {
buf = buf << 1 | c - '0';
if (--bitsLeft == 0) {
res.append(buf);
buf = 0;
bitsLeft = 8;
}
}
}

QByteArray finish() {
if (bitsLeft < 8) {
res.append(buf << bitsLeft);
buf = 0;
bitsLeft = 8;
}
return res;
}
}

operator+= 将向 buf 添加额外的位,并将完整字节刷新到 res。在该过程结束时,您可能会留下 3 位。 finish 使用一个简单的算法:它用零填充缓冲区以生成最终字节,并将完全编码的缓冲区返回给您。

更复杂的解决方案可能是引入源字符集中不存在的显式“流结束”标记。

关于c++ - 字符串转为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70393068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com