如何在Python中表达二进制文字?
它们不是“二进制”字面量,而是“整数字面量”。您可以用二进制格式表示整数字面量,即0后跟B或B后跟一系列0和1,例如:
>>> 0b0010101010
170
>>> 0B010101
21
在Python 3文档中,以下是在Python中提供整数字面量的方法:
Integer literals are described by the following lexical definitions:
integer ::= decinteger | bininteger | octinteger | hexinteger
decinteger ::= nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger ::= "0" ("b" | "B") (["_"] bindigit)+
octinteger ::= "0" ("o" | "O") (["_"] octdigit)+
hexinteger ::= "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::= "1"..."9"
digit ::= "0"..."9"
bindigit ::= "0" | "1"
octdigit ::= "0"..."7"
hexdigit ::= digit | "a"..."f" | "A"..."F"
There is no limit for the length of integer literals apart from what
can be stored in available memory.
Note that leading zeros in a non-zero decimal number are not allowed.
This is for disambiguation with C-style octal literals, which Python
used before version 3.0.
Some examples of integer literals:
7 2147483647 0o177 0b100110111
3 79228162514264337593543950336 0o377 0xdeadbeef
100_000_000_000 0b_1110_0101
Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.
表示二进制的其他方法:
你可以把0和1放在一个可以被操纵的字符串对象中(尽管在大多数情况下你应该只对整数进行位操作)-只需将0和1组成的字符串和你要从(2)转换的基数传递给int:
>>> int('010101', 2)
21
你可以选择使用0b或0b前缀:
>>> int('0b0010101010', 2)
170
如果传入0作为基数,如果字符串没有指定前缀,它将假设以10为基数:
>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21
从int转换回人类可读的二进制:
你可以将一个整数传递给bin来查看二进制字面值的字符串表示形式:
>>> bin(21)
'0b10101'
你可以结合bin和int来来回执行:
>>> bin(int('010101', 2))
'0b10101'
你也可以使用格式规范,如果你想有最小宽度前面的0:
>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'