0

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

Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
lpares12
  • 3,504
  • 4
  • 24
  • 45

3 Answers3

3

Try out the bin() function.

bin(yourNumber)[2:]

will give you string containing bits for your number.

ifloop
  • 8,079
  • 2
  • 26
  • 35
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
  • thanks! If I operate with this string the `0b` from the start won't interfere with the operation, right? – lpares12 Nov 18 '15 at 09:18
  • What exact operation, do you want to perform ? – Mangu Singh Rajpurohit Nov 18 '15 at 09:18
  • @deuseux12 You can use `print bin(219936353)[2:].zfill(8)` to remove that `0b`. – Avión Nov 18 '15 at 09:20
  • 1
    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. Thanks – lpares12 Nov 18 '15 at 09:22
  • @deuseux12, This doesn't work: `int(bin(1), 10)`. See my answer for the first correct solution: `int('{:b}'.format(1), 10)` => `1`. – 7stud Nov 18 '15 at 09:33
  • @7stud why would interpreting the binary representation as if it was a decimal representation be a useful thing to do? – jonrsharpe Nov 18 '15 at 19:06
  • @johnsharpe, Huh? My answer was the only answer that did what the op asked. If you don't understand why the op wants to round trip a decimal number to a binary string and back to a decimal number, then why don't you ask the op? – 7stud Nov 18 '15 at 20:00
  • @7stud did you read the question? That's not what they want... – jonrsharpe Nov 18 '15 at 23:53
  • @jonrsharpe, The op said, *I want to get this binary string from the 219936353 number*, where ***this*** refers to `1101000110111111011001100001`. Okay??! – 7stud Nov 19 '15 at 04:09
0
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
7stud
  • 46,922
  • 14
  • 101
  • 127
0
>>> bin(219936353)
'0b1101000110111111011001100001'
11thdimension
  • 10,333
  • 4
  • 33
  • 71