Bitwise operation
there is 4 properties and each one of them can be activated. To know which one is activated i receive an int value. Using bitwise and operation i get 1, 2, 4 or 8 each number correspond to an activated property.
if((state & 1) == 1) {
status = 1;
开发者_Python百科 } else if ((state & 2) == 2) {
status = 2;
} else if((state & 4) == 4) {
status = 4;
} else if((state & 8) == 8) {
status = 8;
}
I was wondering if could calculate status with one bitwise operation ? Thanks.
If state
always has exactly one of the four bits set, then your code is not very useful, as it is the same as
status = state;
If state
can have any number of bits set, your code sets status
to the least significant set bit in state
. This can also be done with:
status = state & -state;
精彩评论