Binary Serialization of std::bitset

后端 未结 6 1641
醉酒成梦
醉酒成梦 2020-12-17 16:52

std::bitset has a to_string() method for serializing as a char-based string of 1s and 0s. Obviously, this us

6条回答
  •  生来不讨喜
    2020-12-17 17:25

    Answering my own question for completeness.

    Apparently, there is no simple and portable way of doing this.

    For simplicity (though not efficiency), I ended up using to_string, and then creating consecutive 32-bit bitsets from all 32-bit chunks of the string (and the remainder*), and using to_ulong on each of these to collect the bits into a binary buffer.
    This approach leaves the bit-twiddling to the STL itself, though it is probably not the most efficient way to do this.

    * Note that since std::bitset is templated on the total bit-count, the remainder bitset needs to use some simple template meta-programming arithmetic.

提交回复
热议问题