简体   繁体   中英

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;
                } 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM