这是一种可能的方法,基于一次std::vector<unsigned char>读/写一个位的显式创建...
template<size_t N>
std::vector<unsigned char> bitset_to_bytes(const std::bitset<N>& bs)
{
std::vector<unsigned char> result((N + 7) >> 3);
for (int j=0; j<int(N); j++)
result[j>>3] |= (bs[j] << (j & 7));
return result;
}
template<size_t N>
std::bitset<N> bitset_from_bytes(const std::vector<unsigned char>& buf)
{
assert(buf.size() == ((N + 7) >> 3));
std::bitset<N> result;
for (int j=0; j<int(N); j++)
result[j] = ((buf[j>>3] >> (j & 7)) & 1);
return result;
}
请注意,要调用反序列化模板函数,必须在函数调用中指定位集bitset_from_bytes大小,例如N
std::bitset<N> bs1;
...
std::vector<unsigned char> buffer = bitset_to_bytes(bs1);
...
std::bitset<N> bs2 = bitset_from_bytes<N>(buffer);
如果您真的关心速度,那么一种会有所收获的解决方案是进行循环展开,以便一次完成一个字节的打包,但更好的是编写您自己的不隐藏内部的 bitset 实现二进制表示而不是使用std::bitset.