binarytwos-complementunsigned-integernegationuint32

Is there a way to make Python interpret `~3` as an unsigned integer?


Is there a way to make Python interpret ~3 as an unsigned integer?


Solution

  • Not directly - the expression ~3 is the bitwise inverse of 3, the type of 3 is int and so will the type of ~3 be, so the result is -4.

    Python itself has no unsigned integer type, but common third party libraries like Numpy do:

    import numpy as np
    
    x = np.uint8(3)
    print(~x)
    

    Output:

    252
    

    Which makes sense, since that is the bitwise inverse of 3 as an 8-bit unsigned integer.

    But whether that is what you were looking for exactly is unclear. Whatever type you pick for "3" will change what the bitwise inverse will have as a value.

    Edit: noting the uint32 tag you added to your question, this may be what you're after:

    >>> x = np.uint32(3)
    >>> print(~x)
    4294967292