ID : 128
viewed : 118
Tags : PythonPython IntegerPython Bytes
100
This tutorial introduces how to convert an integer to binary in Python. This tutorial also lists some example codes to elaborate on different ways of conversion from int to binary in Python.
bin()
Function to Convert Int to Binary in PythonIn Python, you can use a built-in function, to convert an integer to binary. The bin()
function takes an integer as its parameter and returns its equivalent binary string prefixed with 0b
.
An example of this is:
binary = bin(16) print(binary)
Output:
0b10000
format
Function to Convert Int to Binary in PythonAs shown above, the binary of an integer can be simply obtained with bin(x)
method. But if you want to remove the 0b
prefix from its output, you can use the format
function and format the output.
format(value, format_spec)
function has two parameters - value
and format_spec
. It will return the formatted output according to the format_spec
. Below are some example formatting types that can be used inside the placeholders:
Formatting Type | Role |
---|---|
= | Places the sign to the leftmost position |
b | Converts the value into equivalent binary |
o | Converts value to octal format |
x | Converts value to Hex format |
d | Converts the given value to decimal |
E | Scientific format, with an E in Uppercase |
X | Converts value to Hex format in upper case |
And there are many more available. As we want to convert int to binary, so b
formatting type will be used.
Below is the code example.
temp = format(10, "b") print(temp)
Output:
1010
str.format()
Method to Convert Int to Binary in PythonThe str.format()
method is similar to the format()
function above and they share the same format_spec
.
Example code to convert int to binary using the str.format()
method is below.
temp = "{0:b}".format(15) print(temp)
Output:
1111