0

I have a vector of bitset<8> that looks like this:

01010110 01010111 01011000 etc..

How can I access the bits two at a time? How can I store two bits in a variable?

For the first element of the vector I want 01, then 01, then 01, then 10 and so on..

Gus
  • 43
  • 7

1 Answers1

0

One simple way I can imagine is doing this:

#include <iostream>
#include <string>
#include <bitset>
#include <vector>

int main() {
    std::vector<std::bitset<8>> vec_b8 {
        std::bitset<8>("01010110"), 
        std::bitset<8>("01010111"), 
        std::bitset<8>("01011000")
    };
    std::vector<std::bitset<2>> vec_b2;

    for(auto b8 : vec_b8) {
        for(size_t i = b8.size() - 2; i > 0; --i) {
            std::bitset<2> b2;
            b2[0] = b8[i];
            b2[1] = b8[i+1];
            vec_b2.emplace_back(b2);        
        }
    }

    for(auto b2 : vec_b2) {
        std::cout << b2.to_string() << " ";
    }
}

The output is

01 10 01 10 01 11 01 10 01 10 01 11 01 10 01 11 10 00 

See the Live Demo.

user0042
  • 7,917
  • 3
  • 24
  • 39