1

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);
14
  • Works fine for me. Commented May 4, 2016 at 18:01
  • I am getting this error "error: no match for call to ‘(std::bitset<128ul>) (uint8_t [16])’" Commented May 4, 2016 at 18:04
  • @DeiDei: It would "work" in the sense that if test was zeroed, some compilers might use the string based constructor, determine it was the empty string (the first byte is NUL), and zero out the bitset; coincidentally correct if test is zeroed, but wrong in all other cases. Commented May 4, 2016 at 18:04
  • @ShadowRanger I assumed that was true when I wrote my comment. It seems the OP is getting a compiler error, which I couldn't reproduce. Commented May 4, 2016 at 18:05
  • 1
    @CPP_NEW Edit the question with the actual code that's giving you a problem. Commented May 4, 2016 at 18:16

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot !! It is somehow working for me now. I will see if I can make it quicker. BTW your English is as good as (or better than) mine :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.