Converting integer to binary in python
>>> '{0:08b}'.format(6)
'00000110'
Just to explain the parts of the formatting string:
{}
places a variable into a string0
takes the variable at argument position 0:
adds formatting options for this variable (otherwise it would represent decimal6
)08
formats the number to eight digits zero-padded on the leftb
converts the number to its binary representation
If you're using a version of Python 3.6 or above, you can also use f-strings:
>>> f'{6:08b}'
'00000110'
Python int to binary string?
Python's string format method can take a format spec.
>>> "{0:b}".format(37)
'100101'
Format spec docs for Python 2
Format spec docs for Python 3
Convert base-2 binary number string to int
You use the built-in int()
function, and pass it the base of the input number, i.e. 2
for a binary number:
>>> int('11111111', 2)
255
Here is documentation for Python 2, and for Python 3.
Converting a calculated decimal number into 8 bit binary
You do have to print the value:
>>> print(bin(160)) # This version gives the 0b prefix for binary numbers.
0b10100000
>>> print(format(160,'08b')) # This specifies leading 0, 8 digits, binary.
10100000
>>> print('{:08b}'.format(160)) # Another way to format.
10100000
>>> print(f'{160:08b}') # Python 3.6+ new f-string format.
10100000
Converting a number to binary with a variable length
You can nest {}
formats in f-strings:
>>> s = 6
>>> l = 7
>>> a = f'{s:0{l}b}'
>>> print(a)
0000110
Converting an Integer to Binary in Python
- Removed recursion.
- Condition should be
num != 0
. - Use
divmod
built-in function for getting both quotient and remainder. - Removed redundant
modnum
checks.
Assuming these issues we can write
def func(num):
if num == 0:
return [num]
binary_digits = []
while num != 0:
num, modnum = divmod(num, 2)
binary_digits.append(modnum)
return list(reversed(binary_digits))
num = int(input("Enter the Number"))
binary_digits = func(num)
print(binary_digits)
Example:
>>> func(100)
[1, 1, 0, 0, 1, 0, 0]
Convert integer to binary and then do a left bit shift in python
You can do the bit shift before converting to binary, since the bit shifting doesn't care about the base of your integer (bit shifting is by definition done in the base of 2).
i = 6 << 12
answer = bin(i)[2:]
Edit: Alternative binary conversion from @guidot
i = 6 << 12
answer = "{:b}".format(i)
Additional conversions
Just for the fun of it, here's some other ways to bit shift a number:
i = 6 * (2**12) # This will convert into 6 * 2^12
answer = "{:b}".format(i)
A bit shift will double the numbers value, so by multiplying the bitshift with the power two we achieve the same thing:
> print(6 << 12)
24576
> print(6 * 2**12)
24576
It's generally better to use bit shift if you know you only want to double the value.
You can also convert it to binary and then add 13 trailing zeroes, a funky way to achieve the same functionality:
i = 6 # Notice: No operation here this time
answer = "{:b}".format(i) + ('0' * 12)
Maybe not recommended to use the last method, but it illustrates how (left) bit shifting works.
Converting Integer to Binary Using the Math Module (Python)
Since you say that you are trying to convert the integer 'manually' to binary, I am assuming that you are not willing to use the bin()
function. Here is something you can try.
from math import*
x= int(raw_input('Enter the decimal number'))
n=[]
while x>1:
y=int(x%2)
n=n+[y]
x=floor(x/2.0)
if x==1:
n=n+[1]
elif x==0:
n=n+[0]
size=len(n)
print 'binary equivalent =',
y=-1
while y>=-size:
print n[y],
y=y-1
print ''
Related Topics
How to Execute Raw SQL in Flask-Sqlalchemy App
How to Load All Entries in an Infinite Scroll at Once to Parse the HTML in Python
Shutting Down Computer (Linux) Using Python
Run a Linux System Command as a Superuser, Using a Python Script
How to Create a Reference to a Variable in Python
How to Get a List of All the Duplicate Items Using Pandas in Python
Typeerror: Unhashable Type: 'Dict'
How to Change Backends in Matplotlib/Python
Are Tuples More Efficient Than Lists in Python
Parse HTML Table to Python List
Importerror: Libcblas.So.3: Cannot Open Shared Object File: No Such File or Directory
Python Requests. 403 Forbidden
Converting Integer to Binary in Python
How to Use Subprocess Popen Python
Parsing Date/Time String with Timezone Abbreviated Name in Python