postgresqlintegertilde

when I write SELECT ~1; on Postgresql it gives me -2 as a result. What is the reason of this? And it keeps going for ~4 and -5 etc


I was looking for sql basics and I decided to write SELECT ~1; on postgresql and as a result it returned -2. When i tried this for bigger number it always returned me integer's next integer and negative (~300 and -301). I wonder what's the reason.


Solution

  • ~ evidently is the bitwise negation operator. 1 = 0b00001, ~1 = 0b111...110 = -2.

    This is also called the ones' complement. As you know the numbers use two's complement as representation for negative numbers (as then -0 == 0):

    -x == ~x+1
    ~x == -x-1