This concise article shows you two approaches to converting an integer to binary in Python.
Using the bin() function
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.
number = 1985 # Convert the number to binary binary = bin(number) # Remove the '0b' prefix binary = binary[2:] print(binary)
Using the format() function with binary specifier
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.
# 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)