So I have this operation in python x = int(v,base=2) which takes vas a Binary String. What would be the inverse operation to that?
For example, given 1101000110111111011001100001 it would return 219936353, so I want to get this binary string from the 219936353 number.
Thanks
3 Answers
Try out the bin() function.
bin(yourNumber)[2:]
will give you string containing bits for your number.
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 that 0b.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 to explain your solution a bit?
num = 219936353
print("{:b}".format(num))
--output:--
1101000110111111011001100001
The other solutions are all wrong:
num = 1
string = 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 = 1
string = bin(1)
result = int(string[2:], 10)
print(result) #=> 1