将字节数组转换为Bitset [英] Convert Byte Array into Bitset
本文介绍了将字节数组转换为Bitset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由随机数生成器生成的字节数组。我想把它放入STL bitset中。
I have a byte array generated by a random number generator. I want to put this into the STL bitset.
不幸的是,Bitset看起来只支持下面的构造函数:
Unfortunately, it looks like Bitset only supports the following constructors:
- 1和0的字符串,如10101011
- 无符号长整型。 (我的字节数组会更长)
现在我想到的唯一解决方案是逐位读取字节数组,一个1和0的字符串。有没有人有更有效的解决方案?
The only solution I can think of now is to read the byte array bit by bit and make a string of 1's and 0's. Does anyone have a more efficient solution?
推荐答案
(不知道模板魔术在这里是否如我所料,我在C ++中生锈了。)
Something like this? (Not sure if template magic works here as I'd expect. I'm rusty in C++.)
std::bitset bytesToBitset<int numBytes>(byte *data)
{
std::bitset<numBytes * CHAR_BIT> b;
for(int i = 0; i < numBytes; ++i)
{
byte cur = data[i];
int offset = i * CHAR_BIT;
for(int bit = 0; bit < CHAR_BIT; ++bit)
{
b[offset] = cur & 1;
++offset; // Move to next bit in b
cur >>= 1; // Move to next bit in array
}
}
return b;
}
这篇关于将字节数组转换为Bitset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文