【问题标题】:How to store Huffman's transformed binary code?如何存储霍夫曼转换后的二进制代码?
【发布时间】:2018-04-16 14:02:13
【问题描述】:

我有一个例子:

string str = "01100111 011011 011 0110011011 0111101 "

没有数据类型可以保留。

首先,我动态分配三个字节;

BYTE* store = new BYTE[3];

其次,输入二进制代码

第三,如果大于指定大小,则增加3个字节。

如何编码?

【问题讨论】:

  • 检查移位运算符
  • 研究使用std::bitset
  • 您只想一次查看一个字符,反过来看一个字符串。这意味着您想查看std::string::rbegin()
  • 为什么要分配3个字节?而不是,比如说,5?

标签: c++ bit huffman-code


【解决方案1】:

你有几个选择:

1) 使用std::vector<bool>

这可能是最类似于 C++ 的方式。 std::vector 专门用于bools,它将每个布尔值存储为位。它还会为您分配内存,因此如果有更多位,您不必担心调整向量的大小。

有一个缺点是必须通过引用类来直接访问位,并且使用带有std::vector<bool> 的位运算符有点尴尬。

2) 移位运算符

C++ 还具有可用于移动位的运算符<<>><<=>>=<< 运算符将所有位向左移动,>> 将它们向右移动。 <<=>>=<<>>,就像 +=+

以下是其中的一个示例:

unsigned char bits = 0b10010010 // uses binary literal syntax
bits <<= 1 // each bit in the variable is shifted left by one, making
           // the bits be `00100100`. Note that the overflow is ignored.

bits >>= 2 // bits is now `00001001`

您可以将它们与 AND 和 OR 运算符(|&amp;)结合使用来操作位。

此外,虽然这不能单独完美地解决您的问题,但您还可以使用 std::bitset 来表示位。不过,您仍然必须使用按位移位运算符。

【讨论】:

    【解决方案2】:

    标准库中有一个数据类型std::bitset;不幸的是,它的大小必须是constexpr,这样您就无法动态定义它(例如,取决于您的内容/字符串的大小)。

    实现您想要的行为的一种方法是使用std::vector&lt;bool&gt;

    int main() {
        string str = "01100111 011011 011 0110011011 0111101 ";
    
        //bitset<70> bits(str); // requires 70 as constexpr
    
        vector<bool> bits;
        for (auto c : str) {
            if (c=='1')
                bits.push_back(true);
            else if (c=='0')
                bits.push_back(false);
            else {
                // ignore
            }
        }
    
        for (auto bit : bits) {
            cout << bit;
        }
    
    }
    

    请注意,数据类型 vector&lt;bool&gt; 可以针对速度/内存消耗进行优化,但并非必须如此(例如,cppreference.com - vector):

    std::vector 节省空间的方式(以及 是否完全优化)是实现定义的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多