Python bin() Function
bin() is a built-in Python function that converts an integer to a binary string.
Binary is the most basic number representation in computing, with only two digits: 0 and 1.bin() The function returns a binary string starting with "0b".
Word meaning: bin is short for binary.
Basic syntax and parameters
Syntax format
bin(x)
Parameter Description
- Parameter x:
- Type: integer
- Description: the integer to convert to binary.
Function description
- Return Value: returns a binary string starting with "0b".
Example
Example 1: basic usage
Example
Basic conversions
(
bin
(
0
)
)
Output: 0b0
(
bin
(
1
)
)
Output: 0b1
(
bin
(
2
)
)
Output: 0b10
(
bin
(
8
)
)
Output: 0b1000
(
bin
(
255
)
)
Output: 0b11111111
Negative numbers
(
bin
(
5
)
)
Output: -0b101
Binary of common numbers
(
bin
(
10
)
)
Output: 0b1010
(
bin
(
16
)
)
Output: 0b10000
(
bin
(
100
)
)
Output: 0b1100100
Expected output:
0b0
0b1
0b10
0b1000
0b11111111
-0b101
0b1010
0b10000
0b1100100
Code analysis:
- The returned string starts with "0b", indicating binary.
- Negative numbers show a minus sign.
Example 2: practical applications
Example
Remove the prefix
n
=
42
(
bin
(
n
)
[
2
:
]
)
Output: 101010
Using formatting
(
f
"{n:b}"
)
Output: 101010
Binary operations
a
=
0b1010
10
b
=
0b0101
5
(
f
"a & b = {bin(a & b)}"
)
Output: a & b = 0b0
(
f
"a | b = {bin(a | b)}"
)
Output: a | b = 0b1111
(
f
"a ^ b = {bin(a ^ b)}"
)
Output: a ^ b = 0b1111
Check a bit
n
=
8
0b1000
if
n &
8
:
(
"Bit 4 is 1"
)
Output: Bit 4 is 1
Expected output:
101010
101010
a & b = 0b0
a & b = 0b1111
a ^ b = 0b1111
第4位是1
二进制常用于位运算、权限控制、算法优化等场景。
Python3 内置函数
Python3 built-in function