Question

I have a vector which contains a lot of bools. When I get to 1 in the vector, I start reading the next 8 values as bits - and I want to modify a char according to those 8 values.

Example:

I have a char c = 0; (00000000).

My 8 bits according to the vector are (10101010).

How do I go around assigning these values into the bits of a char? Can I use the vector as a mask? If so, how?

Était-ce utile?

La solution

Use the bit shift operator <<. It shifts bits by a certain amount.

For example, 5 << 2 is 20, because 101 shifted left by two is 10100, or twenty.

vector<bool> v; // plus initialization

char c;   
for(size_t i = 0; i < v.size(); i++) {     
    c += v[i] << (v.size() - i - 1);
}

This assumes you want this big endian (most signitficant bit first). If you want little endian, change (v.size() - i - 1) to i.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top