0

I'm trying to convert a base64 encoded string to its binary form. Basically "cw==" should return 01100110000. I tried various modules but can't seem to find a suitable one. Any one got any ideas?

thanks! j

user3350512
  • 1
  • 1
  • 1
  • possible duplicate of [Convert string to binary in python](http://stackoverflow.com/questions/18815820/convert-string-to-binary-in-python) – isedev Feb 25 '14 at 09:52
  • 1
    `"".join("{0:08b}".format(ord(c)) for c in decodestring("cw=="))` [base64.decodestring] – mshsayem Feb 25 '14 at 10:07
  • [`bin(int(binascii.hexlify(base64.decodestring("cw==")), 16))`](http://stackoverflow.com/q/7396849/4279) – jfs Mar 12 '14 at 10:55
  • `01100110000` doesn't look like correct output: `"cw==" -> "s" -> "\x73" -> 115 -> '0b1110011'` – jfs Mar 12 '14 at 11:10

1 Answers1

1

You must first decode your string

from base64 import decodestring

Then you can use format(ord(x), "b") to produce a binary representation.

my_string = "cw=="
print "".join(format(ord(x), "b") for x in decodestring(my_string))
>> '1110011'
Mp0int
  • 18,172
  • 15
  • 83
  • 114
  • format(ord(x), "b") will not print leading 0s, meaning "AAA" decodes to 000 rather than 000000000000000000000000. See [mshsayem's comment](https://stackoverflow.com/questions/22010277/convert-a-base64-encoded-string-to-binary#comment33362342_22010277) for a better solution. – Crashthatch May 21 '17 at 22:55