将uint8_t数组转换为C++中的位集

convert uint8_t array to bitset in C++

本文关键字:C++ 转换 uint8 数组      更新时间:2023-10-16

有没有一种快速的方法可以将uint8_t的数组转换为biteset。

uint8_t test[16]; 
// Call a function which populates test[16] with 128 bits
function_call(& test);
for(int i=0; i<16; i++)
  cout<<test[0]; // outputs a byte
cout<<endl;
std:: bitset<128> bsTest;

我试过这个,但不起作用

bsTest(test);

我向您提出了一个可能的解决方案。

不太好,不太快,有点脏,但我希望它能有所帮助。

#include <bitset>
#include <iostream>
int main ()
 {
   uint8_t  test[16] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
                         'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' };
   std::bitset<128> bsTest { } ;
   for ( unsigned ui = 0 ; ui < 16 ; ++ui )
    {
      bsTest <<= 8;
      std::bitset<128> bsTmp { (unsigned long) test[ui] };
      bsTest |= bsTmp;
    }
   std::cout << bsTest;
   return 0;
 }

其想法是将位集初始化为零

std::bitset<128> bsTest { } ;

并且在另一比特集结束时一次添加CCD_ 1

std::bitset<128> bsTmp { (unsigned long) test[ui] };

然后合并(比特或)两个比特集

bsTest |= bsTmp;

并将结果移位8位

bsTest <<= 8;

p.s.:很抱歉我的英语不好