Home > front end >  when I write SELECT ~1; on Postgresql it gives me -2 as a result. What is the reason of this? And it
when I write SELECT ~1; on Postgresql it gives me -2 as a result. What is the reason of this? And it

Time:03-29

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.

CodePudding user response:

~ 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
  • Related