为什么 Python 中 ~3 等于 -4?
我正在开始Python 编程。我正在阅读基础教程,但这一点对我来说不是很清楚。我将不胜感激您能给我的任何帮助。
I'm getting started in Python programming. I'm reading a basic tutorial, but this point is not very clear to me. I would appreciate any help you can give me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
~3 表示“反转” 3. 对于自然数数据类型,使用二进制补码,这将变为 - 4、由于二进制表示被反转(所有位都被翻转)。
~3 means 'invert' 3. With two's complement on natural number datatypes, this becomes -4, as the binary representation is inverted (all bits are flipped).
~3 的意思是“把所有的 1 变成 0,0 变成 1”,所以如果 3 的二进制是 0000000000000011,那么 ~3 就是 1111111111111100。由于 ~3 的第一位是 1,所以它是一个负数。为了找出哪个负数,在 2 秒的恭维中,您将所有位反转并加 1,因此反转后我们回到 3,然后加 1 我们得到 4。
~3 means "change all the 1s to 0s and 0s to 1s", so if 3 in binary is 0000000000000011, then ~3 is 1111111111111100. since the first bit of ~3 is a 1, its a negative number. to find out which negative number, in 2s comliment, you invert all bits and add 1, so inverted we are back to 3, then added 1 we get 4.
因为有符号整数通常使用二进制补码存储,这意味着整数的按位逆等于其代数倒数减一。
Because signed integers are usually stored using two's complement, which means that the bitwise inverse of an integer is equal to its algebraic inverse minus one.
它是反转运算符,并返回您给它的数字的按位反转。
It's the invert operator, and returns the bitwise inverse of the number you give it.
不仅仅是Python,它是几乎所有现代计算机的整数数字表示形式:二进制补码。根据二进制补码的定义,通过对正数求补并加一即可得到负数。在您的示例中,您用
~
进行补充,但没有加一,因此您得到了数字减一的负数。It's not just Python, it's the integer numeric representation of almost all modern computers: two's complement. By the definition of two's complement, you get a negative number by complementing the positive number and adding one. In your example, you complemented with
~
but did not add one, so you got the negative of your number minus one.