Python中按位NOT的含义 [英] The meaning of Bit-wise NOT in Python

查看:131
本文介绍了Python中按位NOT的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么按位不不能按预期方式切换位?参见以下示例:

Why bitwise not does not act as expected for toggling bits? See for example below:

a = 5
print(bin(a))
b = ~a
print(bin(b))

这是输出:

0b101
-0b110

问题是为什么左边的第一位没有切换?

The question is why the first bit from the left is not toggled?

考虑到Python文档说:

Considering that Python documentation says:

〜x返回x的补数-切换每个数字得到的数字 1代表0,每个0代表1.

~ x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1.


您是说〜"不是简单切换位的运算符,而是二进制补码的运算符? 如果是这样,为什么文档中引用的句子没有说明这一点. Python文档中的上述句子对我而言并不表示这句话.


Are you saying that "~" is not the operator for simple toggling of bits, but instead it is the operator for twos complement? If so, why the sentence quoted from documentation does not tell that. The sentence above from Python documentation does not imply this to me.

推荐答案

切换所有位. 所有,包括无限数量的前导零,产生无限数量的前导零:

It is toggling all the bits. All of them, including an infinite number of leading zeros, producing an infinite number of leading ones:

0b...111111111111111111111111111111111111111111111111111010

因为Python模拟的是无穷大的表示形式,而不是3位或32位或64位或任何有限数.

because Python simulates an infinite-bit representation, not 3-bit or 32-bit or 64-bit or any finite number.

Python不能向您显示无限多个前导字符,因此,它显示的是bin(abs(b))并在前面带有-符号. abs(b)6bin(6)'0b110',所以您看到了

Python can't show you an infinite number of leading ones, so instead, it shows you bin(abs(b)) with a - sign in front. abs(b) is 6 and bin(6) is '0b110', so you see

-0b110

这篇关于Python中按位NOT的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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