Search code examples
c++bitsetstd-bitset

convert uint8_t array to bitset in C++


Is there a quick way to convert an array of uint8_t to a 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;

I tried this but does not work

bsTest(test);

Solution

  • I propose you a possible solution.

    Not so good, not so quick, a little dirty but I hope it can help.

    #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;
     }
    

    The idea is initialize the bitset to zero

    std::bitset<128> bsTest { } ;
    

    and add a uint8_t at a time at the end of another bitset

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

    then merge (bit or) the two bitsets

    bsTest |= bsTmp;
    

    and shift 8 bit the result

    bsTest <<= 8;
    

    p.s.: sorry for my bad English