Python bin()
Function
The bin() function in Python converts an integer number into a binary string. This is helpful when you want to understand or manipulate numbers in binary format.
Syntax
bin(x)
Parameters:
x
– A non-complex integer number.
Returns:
- A string that starts with
'0b'
followed by the binary representation of the number.
Example 1: Convert Positive Integer to Binary
print(bin(10))
0b1010
Example 2: Convert Negative Integer to Binary
print(bin(-4))
-0b100
Use Case: Binary Representation for Bitwise Operations
a = 5
b = 3
print("Binary of a:", bin(a))
print("Binary of b:", bin(b))
print("a & b:", a & b)
print("Binary of (a & b):", bin(a & b))
Binary of a: 0b101
Binary of b: 0b11
a & b: 1
Binary of (a & b): 0b1
How to Get Binary Without '0b'
binary = bin(7)[2:]
print(binary)
111
Note: [2:]
slices off the '0b'
prefix.
Common Mistakes
- bin() only works on integers. If you pass a float, you'll get a
TypeError
. - It does not pad with leading zeros. Use
format()
if you need fixed-length binary.
Interview Tip
Use bin()
in coding interviews when dealing with bit manipulation problems, such as checking set bits, binary palindromes, or bitwise AND/OR operations.
Summary
bin(x)
converts an integerx
into a binary string.- The result always starts with
'0b'
. - To remove
'0b'
, slice the string using[2:]
. - Only integer types are supported.
Practice Problem
Write a program that asks the user to enter an integer and then prints its binary form (without the '0b'
prefix).
num = int(input("Enter an integer: "))
print("Binary representation:", bin(num)[2:])