The bin() function is the most efficient way to convert an integer to a binary string in Python. It accepts an integer and returns its equivalent binary string, prefixed with ‘0b’.
It works with both positive and negative integers.
In the above figure, we described both types of integers (positive and negative) and converted them into a binary string. Both outputs are different.
positive_num = 22 negative_num = -22 binary_str = bin(positive_num) print(binary_str) # Output: 0b10110 binary_str = bin(negative_num) print(binary_str) # Output: -0b10110
As you can see, both outputs are now binary strings with “0b” prefix.
You can remove the prefix “0b” by slicing the string for the clean output.
positive_num = 22 binary_str = bin(positive_num) binary_str_clean = binary_str[2:] print(binary_str_clean) # Output: 10110
You can see that the output binary string is very clean, which is quick for debugging.
Other approaches
Approach 1: Using f-strings (Python 3.6+)
With the release of Python 3.6, it comes with a new approach called “f-strings”, which is a clean method to embed formatting directly in strings for readability.
By using the format specifier :b within an f-string, an integer can be seamlessly converted into its binary string representation.
positive_num = 22 negative_num = -22 print(f'{positive_num:b}') # Output: 10110 print(f'{negative_num:b}') # Output: -10110
You can see that we don’t need slicing or anything to remove the ‘0b’ prefix because it is not added to the string. It might be the cleanest approach for the conversion.
Approach 2: Using format()
The format() function offers flexibility, including the ability to specify the bit length. This function accepts two parameters: The value to be formatted and the format specifier. It returns the output formatted according to the specified format.
positive_num = 22 negative_num = -22 binary_str = format(positive_num, "b") print(binary_str) # Output: 10110 binary_str = format(negative_num, "b") print(binary_str) # Output: -10110
Specify bit length (e.g., 8 bits)
positive_num = 22 negative_num = -22 binary_str_octal = format(positive_num, '08b') print(binary_str_octal) # Output: 00010110 binary_str_neg_octal = binary_str = format(negative_num, '08b') print(binary_str_neg_octal) # Output: -0010110
The output is an 8-bit binary string.
Approach 3: Using string.format()
The string.format() method formats the specified values and inserts them inside the string’s placeholders, which are defined using curly brackets: {}.
The ‘b’ specifier indicates that the number should be formatted as a binary number.
positive_num = 22 negative_num = -22 print("{0:b}".format(positive_num)) # Output: 10110 print("{0:b}".format(negative_num)) # Output: -10110
That’s all!
SY
Kindof an overkill to use format() to remove the binary string prefix, when you could just use string slicing ‘[2:]’ which is much simpler.