Remi.b Remi.b - 1 month ago 8
C++ Question

From a vector of `int` to a sequence of bits

y
is an unsigned integer which represents a list of bits.
v
is a vector of integers containing only 0 and 1. I would like to set the values of
v
into
y
in an efficient manner. I would do

for (int i ; i<v.size() ; ++i)
{
y ^= (-v[i] ^ y) & (1 << i);
}


Is this efficient or is there a better way to do it?

Answer

"I asked the question mainly to improve my understanding of bitwise manipulations" - If that's the case then: You are using two ^ ops, one & op and one << op, u can achieve the same by using one << op and one | op. Something like this:

for (int i ; i<v.size() ; ++i)
{
    y <<= 1;
    y |= v[i];
}
Comments