为什么 python 按位运算符不使用 bin() returns

Why aren't the python bitwise operators working with what bin() returns

我一直在做一些按位运算符的工作,通常从使用 bin() 转换整数开始。我每次尝试都遇到错误。

foo = 5
binfoo = bin(foo)
bar = ~(binfoo)

最后一行搞砸了。

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary ~: 'str'

如果 bin() returns 一个字符串那么这些按位运算符期望什么?

~ 一元按位运算符需要 整数输入 。来自 Python 参考文档的 表达式 章节的 Unary arithmetic and bitwise operations section

The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers.

大胆强调我的。

~ 应用于 5 效果很好:

>>> ~5
-6

bin()函数只returns一个字符串对象,用数字的二进制表示。将其视为调试工具,它可以快速向您显示已设置和未设置整数的位。要实际操作位,您仍然需要一个整数。