The bin() function converts an integer number to a binary string.
Syntax
bin(number)bin() Parameters
Python bin() function parameters:
| Parameter | Condition | Description |
|---|---|---|
number |
Required | Any integer |
bin() Return Value
Python bin() function returns:
- the binary string equivalent to the given integer
TypeErrorfor a non-integer argument
Examples
bin() function with Integer
For example with positive numbers:
result = bin(65)
print(result) # Output: 0b1000001
result = bin(41)
print(result) # Output: 0b101001output
0b1000001
0b101001But you can also use negative numbers:
result = bin(65)
print(result) # Output: -0b1000001
result = bin(-41)
print(result) # Output -0b101001output
-0b1000001
-0b101001You can use numbers expressed in different formats: hexadecimal (base16) and octal (base 8).
result = bin(0xF)
print(result) # Output: 0b1111
result = bin(0o12)
print(result) # Output: 0b1010bin() function with Non-Integer Class
class Quantity:
apple = 1
orange = 2
grapes = 3
def func():
return apple + orange + grapes
print('The binary equivalent of quantity is:', bin(Quantity()))output
TypeError: 'Quantity' object cannot be interpreted as an integerEquivalent method to convert to binary string
You can achieve the same result by using format() function or f-string.
Using format() function:
result = format(41, '#b')
print(result) # Output: 0b101001
result = format(41, 'b')
print(result) # Output: 101001output
0b101001
101001Using f-string:
result = f'{41:#b}'
print(result) # Output: 0b101001
result = f'{41:b}'
print(result) # Output: 101001