Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python bin() Function

Python bin() Function

Python3 Built-in Functions Python3 built-in 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

- Type: integer - Description: the integer to convert to binary.

Function description


Example

Example 1: basic usage

Example

Basic conversions

print

(

bin

(

0

)

)

     

Output: 0b0

print

(

bin

(

1

)

)

     

Output: 0b1

print

(

bin

(

2

)

)

     

Output: 0b10

print

(

bin

(

8

)

)

     

Output: 0b1000

print

(

bin

(

255

)

)

   

Output: 0b11111111

Negative numbers

print

(

bin

(

5

)

)

   

Output: -0b101

Binary of common numbers

print

(

bin

(

10

)

)

   

Output: 0b1010

print

(

bin

(

16

)

)

   

Output: 0b10000

print

(

bin

(

100

)

)

   

Output: 0b1100100

Expected output:

0b0
0b1
0b10
0b1000
0b11111111
-0b101
0b1010
0b10000
0b1100100

Code analysis:

  1. The returned string starts with "0b", indicating binary.
  2. Negative numbers show a minus sign.

Example 2: practical applications

Example

Remove the prefix

n

=

42

print

(

bin

(

n

)

[

2

:

]

)

 

Output: 101010

Using formatting

print

(

f

"{n:b}"

)

   

Output: 101010

Binary operations

a

=

0b1010

 

10

b

=

0b0101

 

5

print

(

f

"a & b = {bin(a & b)}"

)

 

Output: a & b = 0b0

print

(

f

"a | b = {bin(a | b)}"

)

 

Output: a | b = 0b1111

print

(

f

"a ^ b = {bin(a ^ b)}"

)

 

Output: a ^ b = 0b1111

Check a bit

n

=

8

 

0b1000

if

n &

8

:

   

print

(

"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 内置函数