Search code examples
c#syntaxchipmunk

What is the purpose of this tilde in C#


I'm trying to port this C# code:

public static ulong WILDCARD_COLLISION_TYPE
{
    get
    {
        int parse = ~0;
        return (ulong)parse;
    }
}

If I understand correctly, doesn't the ~ symbol perform a bitwise complement so what is the point of doing ~0? and then returning it?


Solution

  • From the ~ Operator documentation:

    The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, long, and ulong.

    For example:

    unsigned int i = ~0;
    
    Result: Max number I can assign to i
    
    and
    
    signed int y = ~0;
    
    Result: -1
    

    so fore more info we can say that ~0 is just an int with all bits set to 1. When interpreted as unsigned this will be equivalent to UINT_MAX. When interpreted as signed this will be -1