int max = ~0; What does it mean?

前端 未结 8 2004
灰色年华
灰色年华 2021-01-19 03:46

int max = ~0;

What does it mean?

相关标签:
8条回答
  • 2021-01-19 04:45

    As others have stated, ~ is the bitwise negation operator. It will take all bits of the integer value and toggles 0 and 1 (0 -> 1 and 1 -> 0).

    ~0 equals to -1 for a signed integer or Int32.

    Usually either ~0 or -1 is used as the "ALL inclusive" mask (asterisk) when you are implementing a layer-based filtering system of some kind where you use a "layerMask" argument which by default equals to -1 meaning that it will return anything (does not filter). The filter is indeed using a AND operation (valueToFilter & layerMask).

    valueToFilter & -1 will always be non-zero if valueToFilter is also non-zero. Zero otherwise.

    0 讨论(0)
  • 2021-01-19 04:48

    Bitwise complement.
    http://msdn.microsoft.com/en-us/library/d2bd4x66.aspx

    A literal 0 (as in the code above) is an int.
    An int is a 32 bit binary value. The value 0 has all the bits set to 0.

    The ~ operator is a bitwise compliment. i.e. I swaps all the bits.
    As all the bits were 0 they are all turned into 1. So we have a 32 bit value
    with all the bits set to 1.

    C# sharp uses 2 compliment. Which encodes -1 in an int as all bits being 1

    0000 0000 0000 0000 0000 0000 0000 0000   == 0
    
    operator ~
    
    1111 1111 1111 1111 1111 1111 1111 1111   == -1
    

    So => ~0 == -1

    0 讨论(0)
提交回复
热议问题