2

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.

tahayf
  • 23
  • 4

1 Answers1

2

~ 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
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138