CodyBugstein
CodyBugstein

Reputation: 23322

How to convert \x after base64 decoding into something readable?

I'm trying to decode the following Base64 string into readable text.

T2ggeWVhaCEgAQ==

I'm using Python Base64 library to do so. However, when I do, I get:

>>> base64.b64decode("T2ggeWVhaCEgAQ==")
'Oh yeah! \x01'

What is \x01?

How do I decode such that all the text is readable and I don't get any weird symbols?

Upvotes: 0

Views: 4028

Answers (3)

jfs
jfs

Reputation: 414555

'\x01' is a text representation of bytes in Python 2. '\x01' is a single byte. Bytes that are in ASCII printable range represent themselves e.g., you see 'O' instead of '\x4f':

>>> b'\x4f\x68\x20\x79\x65\x61\x68\x21\x20\x01'
'Oh yeah! \x01'

To remove all "weird" bytes (to keep characters from string.printable):

#!/usr/bin/env python
import string

weird = bytearray(set(range(0x100)) - set(map(ord, string.printable)))
print(b'Oh yeah! \x01'.translate(None, weird).decode())
# -> Oh yeah!

string.printable contains some non-printable characters such as '\t' (tab), '\n' (newline). To exclude them too and to leave only printing character:

printing_chars = range(0x20, 0x7e + 1)
weird = bytearray(set(range(0x100)) - set(printing_chars))
print(b'Oh yeah! \x01'.translate(None, weird))
# -> Oh yeah! 

Upvotes: 1

tdelaney
tdelaney

Reputation: 77357

You could filter out the unreadable characters:

from string import printable
print ''.join(c for c in base64.b64decode('T2ggeWVhaCEgAQ==') if c in printable)

Upvotes: 1

user149341
user149341

Reputation:

The last byte of the Base64 encoded data is hex 01. This isn't a printable character in any commonly used encoding; there's no way to make it into "readable text" without turning it into something it isn't.

Upvotes: 0

Related Questions