Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitmask question?

Tags:

I have the follow:

public static final int LIMIT_ONE = 1; public static final int TRADEABLE = (1 << 1); public static final int SELLABLE = (1 << 2); public static final int STORABLE = (1 << 3); public static final int STORABLE_IN_WH = (1 << 4); public static final int STORABLE_IN_LEGION_WH = (1 << 5); public static final int BREAKABLE = (1 << 6); public static final int SOUL_BOUND = (1 << 7); public static final int UNK9 = (1 << 8); public static final int UNK10 = (1 << 9); public static final int UNK11 = (1 << 10); public static final int CAN_COMPOSITE_WEAPON = (1 << 11); public static final int BLACK_CLOUD_TRADERS = (1 << 12); public static final int CAN_SPLIT = (1 << 13); public static final int UNK15 = (1 << 14); public static final int UNK16 = (1 << 15); 

and I wanted to understand how it is calculated to give the follow result, for example: 12414

I am really clueless on how the bitmask work and if any one could perhaps give some tips and explain how it goes to that number I would appreciate very much.

like image 899
Prix Avatar asked Dec 28 '10 20:12

Prix


1 Answers

12414 in binary is:

Binary number: 1  1  0  0  0  0  0  1  1  1  1  1  1  0 ------------------------------------------------------- Bit positions: 13 12 11 10 9  8  7  6  5  4  3  2  1  0 

Look at which bits are 1. Those are the flags that are set in the bitmask, which is created by using the bitwise OR operator to combine the flags:

bitmask = TRADEABLE | SELLABLE | STORABLE | STORABLE_IN_WH | STORABLE_IN_LEGION_WH | BREAKABLE | BLACK_CLOUD_TRADERS | CAN_SPLIT; 

To further explain this, STORABLE = (1 << 3); means that STORABLE is equal to the number one (binary 1, falling only in bit position 0) shifted to the left by 3 places. Note that STORABLE = Math.pow(2, 3); would be equivalent. Because none of the bits overlap among the flags, we can combine all of them into a single int and then split them apart later.

We can check for the existence of flags using the bitwise AND operator, which will return a non-zero value if the flag is set and a zero value if the flag is not set:

if(bitmask & TRADEABLE != 0) {     // This item can be traded } else {     // This item cannot be traded } 

We can set, clear, or toggle flags like this:

bitmask |= TRADEABLE; // Sets the flag using bitwise OR bitmask &= ~TRADEABLE; // Clears the flag using bitwise AND and NOT bitmask ^= TRADEABLE; // Toggles the flag using bitwise XOR  
like image 74
PleaseStand Avatar answered Sep 21 '22 21:09

PleaseStand