Python bin()
Function: Convert Numbers to Binary
The bin()
function in Python converts an integer into its binary representation as a string.
Example
num = 10
print(bin(num))
# Output: '0b1010'
The result starts with 0b
, indicating a binary number.
Syntax
bin(number)
- number: An integer (not a float or string).
- Returns: A binary string prefixed with
0b
.
Why Use bin()
?
1. Binary Representation of Numbers
Helps visualize numbers in binary format.
print(bin(8))
# Output: '0b1000'
2. Removing the 0b
Prefix
Use slicing to remove the prefix and get a clean binary string.
binary_str = bin(15)[2:]
print(binary_str)
# Output: '1111'
3. Converting Back to Integer
Convert a binary string back to an integer using int()
.
binary_value = "1010"
decimal_value = int(binary_value, 2)
print(decimal_value)
# Output: 10
4. Working with Databases (SQL Use Case)
Some databases store binary values. Convert numbers to binary before inserting into a database.
user_id = 25
binary_id = bin(user_id)[2:]
print(f"INSERT INTO users (id_binary) VALUES ('{binary_id}');")
# Output: INSERT INTO users (id_binary) VALUES ('11001');
Key Notes
- ✔ Only works with integers: Floats and strings need conversion first.
- ✔ Returns a string: Useful for display or storage.
- ✔ Binary math: Can be used with bitwise operators.
- ✔ Works with negative numbers: Uses two’s complement representation.
By using bin()
, you can easily work with binary numbers for calculations, databases, and debugging. 🚀