bitmask question?

后端 未结 6 1915
面向向阳花
面向向阳花 2021-01-31 04:46

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


        
6条回答
  •  死守一世寂寞
    2021-01-31 05:03

    In binary, 12414 is 11000001111110. LIMIT_ONE in binary is 1 and the <<, which is the bitshift operator moves the zero to the left padding with a zero on the right. Therefore, tradeable in binary is 10 and so on until unk16, which ends up being 1000000000000000. Now you put these values together using bitwise OR, which basically puts a 1 on each position where at least one of its operand has a one on that position (the pipe operator '|' is used in most languages).

    Example:

    100 | 10 = 110
    

    Therefore, to get to 12414, you need to do a bitwise OR on the following variables: unk16, unk15, tradeable, selleable, storeable, storeable in wh, storeable in legion wh and breakable. The combination of ones on the different positions in each of these variables gives you binary 11000001111110, which turns out to be 12414 in decimal.

    This is probably the simplest way to explain it, if you want to know more, you should read up on bitwise operators and how binary representation of numbers works.

    To find out which of the flags the number 12414 has, you can use the & (bitwise AND) operator and do a zero check. For example:

    6 & 2 = 2 (110 has a 1 on the same position as 2, which is 010)
    6 & 1 = 0 (110 does not have a 1 on the same position as 1, which is 001)
    

提交回复
热议问题