Skip to content

Python bin() Function

How to convert integers to binary strings in Python using the built-in bin() function, including handling positive/negative numbers, hex/octal inputs, and avoiding TypeError with custom classes.

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
  • 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).

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

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

Equivalent 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: 101001

output

0b101001
101001

Using f-string:

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

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