Convert an integer to a binary string in Python
This post will discuss how to convert an integer to a binary string in Python.
1. Using str.format() function
A simple solution is to use the str.format() function, which performs a string formatting operation. To convert the integer to its binary representation, you can use the string presentation type b.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 100 binary = "{0:b}".format(x) print(binary) # 1100100 |
To get the binary string of specified length left-padded with all zeros, you can change the formatting specification to {0:08b}:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 100 binary = '{0:08b}'.format(x) print(binary) # 01100100 |
2. Using f-strings
Starting with Python 3.6, you can use f-strings. This can be done by prefixing the string literal with f or F. Here’s how the code would look like:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 100 binary = f'{x:08b}' print(binary) # 01100100 |
3. Using format() built-in function
Another option is to use the built-in function format(value[, format_spec]) which converts the specified value to a formatted string according to the formatting specification format_spec. Here’s an example of its usage:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 100 binary = format(x, "08b") print(binary) # 01100100 |
4. Using bin() built-in function
Finally, you may use the built-in function bin(), which converts an integer to a binary string prefixed with 0b. You can use slicing to get rid of the prefix, as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 100 binary = bin(x)[2:] print(binary) # 1100100 |
To get the binary string of specified length left-padded with zeros, you can use the zfill() function:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 100 binary = bin(x)[2:].zfill(8) print(binary) # 01100100 |
That’s all about converting an integer to a binary string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)