⬅ Previous Topic
Python ascii() Function – Get ASCII Representation of ObjectsNext Topic ⮕
Python bool() Function – Convert to Boolean⬅ Previous Topic
Python ascii() Function – Get ASCII Representation of ObjectsNext Topic ⮕
Python bool() Function – Convert to Booleanbin()
FunctionThe 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.
bin(x)
x
– A non-complex integer number.'0b'
followed by the binary representation of the number.print(bin(10))
0b1010
print(bin(-4))
-0b100
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
binary = bin(7)[2:]
print(binary)
111
Note: [2:]
slices off the '0b'
prefix.
TypeError
.format()
if you need fixed-length binary.Use bin()
in coding interviews when dealing with bit manipulation problems, such as checking set bits, binary palindromes, or bitwise AND/OR operations.
bin(x)
converts an integer x
into a binary string.'0b'
.'0b'
, slice the string using [2:]
.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:])
⬅ Previous Topic
Python ascii() Function – Get ASCII Representation of ObjectsNext Topic ⮕
Python bool() Function – Convert to BooleanYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.