bitmask question?

后端 未结 6 1918
面向向阳花
面向向阳花 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:16

    The expression (1 << n) is equivalent to 2 raised to the power of n.

    When you write (1 << n) | (1 << m) this is the same as (1 << n) + (1 << m) as long as n and m are different. So you can think of it in terms of simple additions if you wish.

    The number 12414 in binary is 11000001111110 so it is the sum (or bitwise OR) of the following flags:

    TRADEABLE                1 << 1  =     2
    SELLABLE                 1 << 2  =     4
    STORABLE                 1 << 3  =     8
    STORABLE_IN_WH           1 << 4  =    16
    STORABLE_IN_LEGION_WH    1 << 5  =    32
    BREAKABLE                1 << 6  =    64
    BLACK_CLOUD_TRADERS      1 << 12 =  4096
    CAN_SPLIT                1 << 13 =  8192
    ========================================
                             Total   = 12414
    

    Note that the flags that are included correspond to the bits that are set in the binary representation of 12414, when read right-to-left.

提交回复
热议问题