This concise article shows you two approaches to converting an integer to binary in Python.
Using the bin() function
The bin()
function takes an integer as input and returns a string representing the binary value. That resulting string starts with the 0b
prefix. You can easily remove it by using string slicing as needed.
Example:
number = 1985
# Convert the number to binary
binary = bin(number)
# Remove the '0b' prefix
binary = binary[2:]
print(binary)
Output:
11111000001
Using the format() function with binary specifier
The format()
function can be used to turn an integer into its binary representations. Just pass the number as the first argument and specify the format specifier b
to indicate binary.
Code example:
# Possitive integer to binary
possitive_int = 2023
possitive_binary = format(possitive_int, 'b')
print(possitive_binary)
# Negative integer to binary
negative_int = -2023
negative_binary = format(negative_int, 'b')
print(negative_binary)
Output:
11111100111
-11111100111
Done!