Python bin() Function

Convert an integer number to a binary string

Usage

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

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

Syntax

bin(number)

Python bin() function parameters
ParameterConditionDescription
numberRequiredAny integer

Examples

x = bin(42)
print(x)
# Prints 0b101010

You can pass a negative number to the function.

x = bin(-42)
print(x)
# Prints -0b101010

A number can be in hexadecimal (base 16) and octal (base 8) formats.

# hex
x = bin(0xF)
print(x)
# Prints 0b1111

# octal
x = bin(0o12)
print(x)
# Prints 0b1010

Equivalent Method

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

# using format() function

# with prefix
x = format(42, '#b')
print(x)
# Prints 0b101010

# without prefix
x = format(42, 'b')
print(x)
# Prints 101010
# using f-string

# with prefix
x = f'{42:#b}'
print(x)
# Prints 0b101010

# without prefix
x = f'{42:b}'
print(x)
# Prints 101010