当我写 SELECT ~1;结果在 Postgresql 上它给了我 -2。这是什么原因呢?它一直持续到 ~4 和 -5 等

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

我正在寻找 sql 基础知识,我决定在 postgresql 上编写 SELECT ~1;,结果它返回 -2。当我尝试这个更大的数字时,它总是返回整数的下一个整数和负数(~300 和 -301)。请问是什么原因

~ 显然是 bitwise negation 运算符。 1 = 0b00001, ~1 = 0b111...110 = -2.

这也称为一的补码。如您所知,数字使用 two's complement 作为负数的表示(当时 -0 == 0):

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