为什么〜True导致

编程入门 行业动态 更新时间:2024-10-25 13:30:29
本文介绍了为什么〜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/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导致

本文发布于:2023-11-24 21:22:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626883.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:True

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!