为什么〜True导致-2? [英] Why does ~True result in -2?

查看:93
本文介绍了为什么〜True导致-2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python控制台中:

In Python console:

~True

给我:

-2

为什么?有人可以用二进制给我解释这个特殊情况吗?

Why? Can someone explain this particular case to me in binary?

推荐答案

int(True) 1

1 是:

00000001

〜1 是:

11111110

-2 ://en.wikipedia.org/wiki/Two%27s_complement rel = noreferrer>双向补数 1

Which is -2 in Two's complement1

1 翻转所有位,将结果加1,并将结果解释为幅度的二进制表示,并添加一个负号(因为数字以1开头) :

1 Flip all the bits, add 1 to the resulting number and interpret the result as a binary representation of the magnitude and add a negative sign (since the number begins with 1):

11111110 → 00000001 → 00000010 
         ↑          ↑ 
       Flip       Add 1

该数字为2,但由于 MSB 为1。

Which is 2, but the sign is negative since the MSB is 1.

值得一提的是:

想想布尔,您会发现它本质上是数字-它有两个值, True False ,它们只是自定义整数1和0的版本,它们的打印方式不同。它们是整数类型 int 子类

Think about bool, you'll find that it's numeric in nature - It has two values, True and False, and they are just "customized" versions of the integers 1 and 0 that only print themselves differently. They are subclasses of the integer type int.

所以它们的行为与1完全相同和0,除了 bool str repr 重新定义为

So they behave exactly as 1 and 0, except that bool redefines str and repr to display them differently.

>>> type(True)
<class 'bool'>
>>> isinstance(True, int)
True

>>> True == 1
True
>>> True is 1  # they're still different objects
False

这篇关于为什么〜True导致-2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆