Pergunta

I have a quite big bitset:

bitset<128*8> bs;

i would like to have access to groups of 8 bits. What of though of so far:

  1. bs.to_string()
  2. split into a vector of string of size 8
  3. create a new bitset from these strings and call to_ulong()

Is there a better solution? Performance is crucial, since i call this method multiple times in my program.

Foi útil?

Solução

std::bitset has operator >>.

If you want just access to the value and read it, you can use below code. It reads N th 8 bit as a uint8_t:

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

Outras dicas

You can do something like this to avoid creating strings 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 need to work on the indices depending on your endianness

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top