Skip to main content

Python bin() Function

The bin() function converts an integer number to a binary string.

note

The result will always be prefixed with '0b'.

Syntax

bin(number)

bin() Parameters

Python bin() function parameters:

ParameterConditionDescription
numberRequiredAny integer

bin() Return Value

Python bin() function returns:

  • the binary string equivalent to the given integer
  • TypeError for 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: 0b101001

output

0b1000001
0b101001

But you can also use negative numbers:

result = bin(65)
print(result) # Output: -0b1000001

result = bin(-41)
print(result) # Output -0b101001

output

-0b1000001
-0b101001

You can use numbers expressed in different formats: hexadecimal (base16) and octal (base 8).

# hex
result = bin(0xF)
print(result) # Output: 0b1111

# octal
result = bin(0o12)
print(result) # Output: 0b1010

bin() 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 integer
note

This TypeError can be fixed by using the Python __index__() method with a non-integer class.

class Quantity:
apple = 1
orange = 2
grapes = 3

def __index__(self):
return self.apple + self.orange + self.grapes

print('The binary equivalent of quantity is:', bin(Quantity()))

output

The binary equivalent of quantity is: 0b110

Equivalent method to convert to binary string

You can achieve the same result by using format() function or f-string.

Using format() function:

# with prefix
result = format(41, '#b')
print(result) # Output: 0b101001

# without prefix
result = format(41, 'b')
print(result) # Output: 101001

output

0b101001
101001

Using f-string:

# with prefix
result = f'{41:#b}'
print(result) # Output: 0b101001

# without prefix
result = f'{41:b}'
print(result) # Output: 101001