C# Left Shift Operator

耗尽温柔 提交于 2019-12-01 06:31:16

Your coworker is essentially using an int in place of a bool[32] to try to save on space. The block of code you show is analogous to

bool[] FRUIT_LAYERS = new bool[32];
FRUIT_LAYERS[LayerMask.NameToLayer("Apple")] = true;
FRUIT_LAYERS[LayerMask.NameToLayer("Banana")] = true;

You might want to consider a pattern more like this:

[Flags]
enum FruitLayers : int
{
    Apple = 1 << 0,
    Banana = 1 << 1,
    Kiwi = 1 << 2,
    ...
}

private readonly FruitLayers FRUIT_LAYERS = FruitLayers.Apple | FruitLayers.Banana;

1 << x is essentially saying "give me a number where the (x+1)-th bit is one and the rest of the numbers are all zero.

x | y is a bitwise OR, so it will go through each bit from 1 to n and if that bit is one in either x or y then that bit will be one in the result, if not it will be zero.

So if LayerMask.NameToLayer("Apple") returns 2 and LayerMask.NameToLayer("Banana") returns 3 then FRUIT_LAYERS will be a number with the 3rd and 4th bits set, which is 1100 in binary, or 12 in base 10.

The code is shifting the binary value 1 to the left, the number of binary places to shift is determined by the Apple and Banana, after both values are shifted the are ORed in a binary way

Example: Assume apple returns 2 and banana returns 3 you get: 1 << 2 which is 0100 (that means 4 in decimal) 1 << 3 which is 1000 ( that means eight in decimal)

now 0100 bitwise or with 1000 is 1100 which means 12

Martin Prikryl

1 << n is basicaly equivalent to 2n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!