Search code examples
pythonencryptionbinaryctf

How to convert Python binary to ASCII


I have a binary string encrypted with this: ( S is the binary string)

res = ''.join(format(ord(i), 'b') for i in s)

How to I decrypt it?

I tried the following but then the string is empty?

    for i in s:
      res += chr(int(str(i),2))
   print(res)

Solution

  • Use '07b' or '08b' in format while encoding to binary, as it will keep leading zeros and represent number in 7 or 8 bits which will make it easy to decode back. Now we will consider 8 bits at a time as each character is represented in 8 bits now. Use 7 everywhere if you happen to use '07b' in format. Ascii characters need 7 bits to be represented.

    >>> s = "abcde"
    >>> res = ''.join(format(ord(i), '08b') for i in s)
    >>> ans = []
    >>> for i in range(0, len(res), 8):
    ...      ans.append(chr(int(res[i:i+8],2)))
    ... 
    >>> ''.join(ans)
    'abcde'
    

    One liner:

    >>> ''.join([ chr(int(res[i:i+8],2)) for i in range(0,len(res),8)])
    'abcde'
    

    Reference:

    Convert to binary and keep leading zeros in Python

    Is ASCII code 7-bit or 8-bit?