Convert int to binary string in Python
Categories:
Converting Integers to Binary Strings in Python
Learn various methods to convert an integer into its binary string representation in Python, from built-in functions to manual bitwise operations.
Converting an integer to its binary string representation is a common task in programming, especially when dealing with low-level operations, data serialization, or understanding bitwise logic. Python offers several straightforward ways to achieve this, catering to different needs and levels of control. This article will explore the most common and efficient methods.
Using the bin()
Built-in Function
The simplest and most Pythonic way to convert an integer to a binary string is by using the built-in bin()
function. This function takes an integer as an argument and returns its binary representation prefixed with 0b
. This prefix indicates that the string is a binary literal.
num = 10
binary_string = bin(num)
print(binary_string) # Output: 0b1010
num_negative = -5
binary_string_negative = bin(num_negative)
print(binary_string_negative) # Output: -0b101
Basic usage of the bin()
function for positive and negative integers.
bin()
function returns a string with a 0b
prefix. If you need to remove this prefix, you can slice the string: binary_string[2:]
.Using str.format()
or f-strings for Formatting
For more control over the output format, such as specifying the number of bits or removing the 0b
prefix, str.format()
or f-strings (formatted string literals) are excellent choices. The format specifier 'b'
is used to convert an integer to its binary representation.
num = 42
# Using str.format()
binary_formatted = "{:b}".format(num)
print(binary_formatted) # Output: 101010
# Using f-string
binary_fstring = f"{num:b}"
print(binary_fstring) # Output: 101010
# With zero-padding to 8 bits
binary_padded = f"{num:08b}"
print(binary_padded) # Output: 00101010
Formatting binary strings with str.format()
and f-strings, including zero-padding.
Flowchart: Integer to Binary String Formatting
Manual Conversion with Bitwise Operations
While bin()
and str.format()
are generally preferred, understanding how to manually convert an integer to binary using bitwise operations provides insight into the underlying process. This method involves repeatedly checking the least significant bit (LSB) and right-shifting the number.
def int_to_binary_manual(num):
if num == 0:
return "0"
is_negative = False
if num < 0:
is_negative = True
num = abs(num)
binary_string = []
while num > 0:
binary_string.append(str(num % 2)) # Get LSB
num //= 2 # Right shift
result = "".join(binary_string[::-1]) # Reverse and join
return "-" + result if is_negative else result
print(int_to_binary_manual(10)) # Output: 1010
print(int_to_binary_manual(42)) # Output: 101010
print(int_to_binary_manual(0)) # Output: 0
print(int_to_binary_manual(-5)) # Output: -101
Manual conversion of an integer to a binary string using a loop and modulo operations.