int max = ~0; What does it mean?

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

int max = ~0;

What does it mean?

8条回答
  •  我在风中等你
    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

提交回复
热议问题