Bitset is divided into characters

I have a fairly large set of bits:

bitset<128*8> bs; 

I would like to have access to groups of 8 bits. What because of this so far:

  • bs.to_string ()
  • splits into a row vector of size 8
  • create a new bittet from these lines and call to_ulong ()

Is there a better solution? Performance is critical as I call this method several times in my program.

+4
source share
2 answers

std::bitset has a >> operator.

If you just want to access the value and read it, you can use the code below. It reads Nth 8 bits as uint8_t :

 bitset<128*8> mask(0xFF); uint8_t x = ((bs >> N * 8) & mask).to_ulong(); 
+2
source

You can do something similar to avoid creating lines and some copying:

 for (uint32_t i = 0; i < bs.size(); i+=8) { uint32_t uval = 0; for (uint32_t j = 0; j < 8; j++) { uval = (uval << 1) + bs[i + 7 - j]; } std::cout << uval << std::endl; } 

but you may have to work with indexes depending on your entity

+1
source

Source: https://habr.com/ru/post/1482763/