stl中bitset默认只支持到string和ulong的转换,对于超过32位的整型就无能为力了,这里写的是一对扩展函数,可以方便地实现bitset到char数组的转换,有了char *再转换为任意类型都很容易了,呵呵。代码如下:
void bitset_2_array(const std::bitset<MAX_BIT_SET_SIZE> &bits, uint32 n_set_size, char *buf, uint32 &n_bytes) { n_bytes = 0; for (int i = 0; i < n_set_size; i += 8) { char ch; for (int j = 0; j < 8; ++j) { if (bits.test(i + j)) // 第i + j位为1 ch |= (1 << j); else ch &= ~(1 << j); } buf[n_bytes++] = ch; } } void array_2_bitset(const char *buf, uint32 n_bytes, std::bitset<MAX_BIT_SET_SIZE> &bits, uint32 &n_set_size) { n_set_size = 0; int n_bits = n_bytes * 8; for (int i = 0; i < n_bytes; ++i) { char ch = buf[i]; int n_offset = i * 8; for (int j = 0; j < 8; ++j) { bits.set(n_offset + j, ch & (1 << j)); // 第j位为是否为1 ++n_set_size; } } }