Binary Serialization of std::bitset

后端 未结 6 1636
醉酒成梦
醉酒成梦 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:22

    This is a possible approach based on explicit creation of an std::vector by reading/writing one bit at a time...

    template
    std::vector bitset_to_bytes(const std::bitset& bs)
    {
        std::vector result((N + 7) >> 3);
        for (int j=0; j>3] |= (bs[j] << (j & 7));
        return result;
    }
    
    template
    std::bitset bitset_from_bytes(const std::vector& buf)
    {
        assert(buf.size() == ((N + 7) >> 3));
        std::bitset result;
        for (int j=0; j>3] >> (j & 7)) & 1);
        return result;
    }
    

    Note that to call the de-serialization template function bitset_from_bytes the bitset size N must be specified in the function call, for example

    std::bitset bs1;
    ...
    std::vector buffer = bitset_to_bytes(bs1);
    ...
    std::bitset bs2 = bitset_from_bytes(buffer);
    

    If you really care about speed one solution that would gain something would be doing a loop unrolling so that the packing is done for example one byte at a time, but even better is just to write your own bitset implementation that doesn't hide the internal binary representation instead of using std::bitset.

提交回复
热议问题