Python bin() Function
bin()It is a built-in function in Python used to convert integers to binary strings.
Binary is the most basic number system representation in computers, consisting of only two digits: 0 and 1.bin()The function returns a binary string starting with "0b".
Word Meaning: binIt is the abbreviation of binary.
Basic Syntax and Parameters
Syntax Format
bin(x)
Parameter Description
- Parameter x:
- Type: Integer
- Description: The integer to be converted to binary.
Function Description
- Return Value: Returns a binary string starting with "0b".
Examples
Example 1: Basic Usage
Examples
# Basic conversion
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
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:
- The returned string starts with "0b", indicating binary.
- Negative numbers will display a minus sign.
Example 2: Practical Application
Examples
# Remove 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 bit
n = 8 # 0b1000
if n & 8:
print("The 4th bit is 1") # Output: The 4th bit is 1
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 bit
n = 8 # 0b1000
if n & 8:
print("The 4th bit is 1") # Output: The 4th bit is 1
Expected output:
101010 101010 a & b = 0b0 a & b = 0b1111 a ^ b = 0b1111 第4位是1Binary is commonly used in scenarios such as bit operations, permission control, and algorithm optimization.
Python3 Built-in Functions