Skip to main content

bin()

The bin() function is a built-in Python function that converts an integer number into a binary string prefixed with '0b'. For example, bin(5) returns '0b101'.

Parameter Values

Parameter Description
number

An integer number whose binary representation is to be returned

Return Values

The bin() function returns a string in the format '0bxxx', where 'xxx' is the binary representation.

How to Use bin() in Python

Example 1:

The bin() function converts an integer number to a binary string prefixed with '0b'.

number = 10
binary_string = bin(number)
print(binary_string)
Example 2:

The bin() function works with negative integers as well, using two's complement representation.

number = -5
binary_string = bin(number)
print(binary_string)
Example 3:

You can use bin() in conjunction with string formatting to get a specific binary representation format.

number = 42
formatted_binary = '{:08b}'.format(number)
print(formatted_binary)