This question already has answers here:
Convert int to binary string in Python (36 answers)
Closed10 years ago.
So I have this operation in pythonx = int(v,base=2) which takesvas a Binary String. What would be the inverse operation to that?For example, given1101000110111111011001100001 it would return219936353, so I want to get this binary string from the219936353 number.Thanks
3 Answers3
Try out the bin() function.
bin(yourNumber)[2:]will give you string containing bits for your number.
answeredNov 18, 2015 at 9:06
Mangu Singh Rajpurohit
11.5k4 gold badges76 silver badges101 bronze badges
Sign up to request clarification or add additional context in comments.
9 Comments
lpares12
thanks! If I operate with this string the
0b from the start won't interfere with the operation, right?Mangu Singh Rajpurohit
What exact operation, do you want to perform ?
Avión
@deuseux12 You can use
print bin(219936353)[2:].zfill(8) to remove that0b.lpares12
okey. That binary string is the conversion from the word "hola" to binary. So I would have to convert the binary string to the word. If it gives any problem I'll use Borja solution to take the
0b out. Thanks7stud
@deuseux12, This doesn't work:
int(bin(1), 10). See my answer for the first correct solution:int('{:b}'.format(1), 10) =>1.|
>>> bin(219936353)'0b1101000110111111011001100001'1 Comment
Markus W Mahlberg
Mind toexplain your solution a bit?
num = 219936353print("{:b}".format(num))--output:--1101000110111111011001100001The other solutions are all wrong:
num = 1string = bin(1)result = int(string, 10)print(result)--output:--Traceback (most recent call last): File "1.py", line 4, in <module> result = int(string, 10)ValueError: invalid literal for int() with base 10: '0b1'You would have to do this:
num = 1string = bin(1)result = int(string[2:], 10)print(result) #=> 1Comments
Explore related questions
See similar questions with these tags.


