位掩码问题?

2022-09-01 21:47:39

我有以下几点:

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

我想了解如何计算它以给出以下结果,例如:12414

我对位掩码的工作原理一无所知,如果有人能给出一些提示并解释它如何达到这个数字,我将不胜感激。


答案 1

二进制中的 12414 是:

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

看看哪些位是 1。这些是在位掩码中设置的标志,该位掩码是通过使用按位 OR 运算符组合这些标志而创建的:

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

为了进一步解释这一点,意味着STORABLE等于数字1(二进制1,仅落在位位置0)向左移动3位。请注意,这将是等效的。由于标志之间没有一个位重叠,我们可以将它们全部组合成一个int,然后稍后将它们分开。STORABLE = (1 << 3);STORABLE = Math.pow(2, 3);

我们可以使用按位 AND 运算符检查标志是否存在,如果设置了标志,它将返回非零值,如果未设置标志,则返回零值:

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

我们可以像这样设置、清除或切换标志:

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 

答案 2

表达式等效于 2 提高到 n 的幂。(1 << n)

当你写这个是一样的,只要和不同。因此,如果您愿意,可以从简单的添加方式来考虑它。(1 << n) | (1 << m)(1 << n) + (1 << m)nm

二进制数字是这样的,它是以下标志的总和(或按位 OR):1241411000001111110

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

请注意,当从右向左读取时,包含的标志对应于在 12414 的二进制表示形式中设置的位。


推荐