Home  >  Article  >  Backend Development  >  Use of bitwise negation operator

Use of bitwise negation operator

藏色散人
藏色散人Original
2019-06-03 14:21:498760browse

Use of bitwise negation operator

The use of bitwise negation operator

The bitwise negation operator is based on each binary Bit inversion, such as byte type, the result of ~0 is 255.

This function can do some reversal operations in the mask

In the following code, a stores three values ​​​​2, 4, and 8. Use the bitwise negation '~' operator to reverse

The printed result is false,flase,false,true,true. Mask has been reversed

class Program
{
    static void Main(string[] args)
    {
        byte a = 2 | 4 | 8;
        byte b = (byte)~a;
        Console.WriteLine((b & 2) == 2);
        Console.WriteLine((b & 4) == 4);
        Console.WriteLine((b & 8) == 8);
        Console.WriteLine((b & 16) == 16);
        Console.WriteLine((b & 32) == 32);
        Console.Read();
    }
}

For example, in the unity engine, this operation can be used on LayerMask:

public class LayerMaskTest : MonoBehaviour
{
    public LayerMask layerMask;
    
    void OnEnable()
    {
        layerMask.value = ~layerMask.value;
    }
}

Use of bitwise negation operator

The above is the detailed content of Use of bitwise negation operator. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn