C # shift operator

Here is an expression written by my colleague that I do not quite understand. Unfortunately, it is not available right now, so here it is (with the changed names, we are working on a game in Unity).

private readonly int FRUIT_LAYERS = (1 << LayerMask.NameToLayer("Apple")) | (1 << LayerMask.NameToLayer("Banana")); 

NameToLayer takes a string and returns an integer. I have always seen left shift operators used with a constant integer on the right, and not on the left, and all the examples that I find using Google follow this approach. In this case, I think that he was pushing Apple and Banana to the same relative layer (which I will use later for filtering). There will be more โ€œfruitsโ€ to filter in the future. Any brilliant stackoverflowers that can give me an explanation of what happens on these lines?

+4
source share
4 answers

Your colleague essentially uses int instead of bool[32] to try to save space. The code block that you show is similar

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

You might want to consider a template like this:

 [Flags] enum FruitLayers : int { Apple = 1 << 0, Banana = 1 << 1, Kiwi = 1 << 2, ... } private readonly FruitLayers FRUIT_LAYERS = FruitLayers.Apple | FruitLayers.Banana; 
+3
source

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

x | y x | y is a bitwise OR, so it will go through each bit from 1 to n, and if this bit is one of x or y , then this bit will be one of the results if it is not equal to zero.

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

+7
source

The code shifts the binary value 1 to the left, the number of binary shift places is determined by Apple and Banana, after shifting both ORed values โ€‹โ€‹in binary

Example: Suppose an apple returns 2 and 3 banana returns you get: 1 <2, which is 0100 (which means 4 in decimal) 1 <3, which is 1000 (this means eight in decimal)

now 0100 bitwise or from 1000 is 1100, which means 12

+2
source

1 <n is basically equivalent to 2 n

+2
source

All Articles