你如何在Python中表达二进制文字？

``````>>> 0x12AF
4783
>>> 0x100
256
``````

``````>>> 01267
695
>>> 0100
64
``````

• Python 2.5及更早版本：可以使用`int('01010101111',2)`表示二进制文件，但不能使用文字表达。
• Python 2.5及更早版本：无法表达二进制文字。
• Python 2.6 beta：您可以这样做：`0b1100111``0B1100111`
• Python 2.6 beta：也允许`0o27``0O27`（第二个字符是字母O）来表示八进制。
• Python 3.0 beta：与2.6相同，但不再允许octals的旧`027`语法。

8 个答案:

``````>>> 0b101111
47
``````

``````>>> bin(173)
'0b10101101'
``````

``````>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255
``````

如何在Python中表达二进制文字？

``````>>> 0b0010101010
170
>>> 0B010101
21
``````

``````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"
``````

``````7     2147483647                        0o177    0b100110111
100_000_000_000                   0b_1110_0101
``````

表达二进制的其他方式：

``````>>> int('010101', 2)
21
``````

``````>>> int('0b0010101010', 2)
170
``````

``````>>> int('10101', 0)
10101
>>> int('0b10101', 0)
21
``````

从int转换回人类可读二进制文件：

``````>>> bin(21)
'0b10101'
``````

``````>>> bin(int('010101', 2))
'0b10101'
``````

``````>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))
'0000010101'
>>> format(int('010101', 2), '010b')
'0000010101'
``````

0指定基数是8（而不是10），这很容易看出：

``````>>> int('010101', 0)
4161
``````

``````>>> int('10101', 0)
10101
``````

``````>>> 0b101111
47

>>> int('101111',2)
47
``````

``````>>> bin(47)
'0b101111'
``````

``````>>> int('101111',0)
101111
``````

``````def getInt(binNum = 0):
return eval(eval('0b' + str(n)))
``````