unsigned int v = w;
v[i] = 1; // error, v is not an array
This is not correct because v
is not an array. The solution might be using a std::bitset
or simply shifting bits and using some bit manipulation - this would be faster.
unsigned int setBit(unsigned int w,unsigned int i) {
unsigned int v = ( w |= 1 << i);
return v;
}
usage:
int main(int argc, char *argv[])
{
unsigned int in = 0;
unsigned int res = setBit(in,1); // set 1st bit in 0 to 1, results in 2
return 0;
}
meaning of unsigned int v = ( w |= 1 << i);
| - the bitwise OR
<< - the bitwise shift
v = ( w |= 1 << i)
is the same as v = ( w = w | 1 << i)
so it means: v
is equal to (take w
and OR
it with 1
left shifted by i
, and assign this to w
)
about C/C++ bit manipulation