I tried to design a program that will return the original 32bit value w
but change the number i
element to 1
. Here's the function I got so far. But for this part, v[i]=1;
, it just says that for i
expression must have pointer to object type.
unsigned int setBit(unsigned int w,unsigned int i)
{
unsigned int v = w;
v[i]=1;
return v;
}
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
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments