I have a base64 encoded string S="aGVsbG8=", now i want to decode the string into ASCII, UTF-8, UTF-16, UTF-32, CP-1256, ISO-8659-1, ISO-8659-2, ISO-8659-6, ISO-8659-15 and Windows-1252, How i can decode the string into the mentioned format. For UTF-16 I tried following code, but it was giving error "'bytes' object has no attribute 'deocde'". base64.b64decode(encodedBase64String).deocde('utf-8')
Asked
Active
Viewed 3,050 times
0
-
The error gives a hint: `deocde` does not exist. `deocde` should be `decode` – fredtantini Sep 30 '14 at 18:32
-
Plus, that won't give you UTF-16. – Ignacio Vazquez-Abrams Sep 30 '14 at 20:46
-
Please make your question more readable by putting the error between backticks `` and mark the code as code using the {} button. Also correct the spelling error. – Terry Jan Reedy Sep 30 '14 at 21:02
1 Answers
0
Please read the doc or docstring for the 3.x base64 module. The module works with bytes, not text. So your base64 encoded 'string' would be a byte string B = b"aGVsbG8"
. The result of base64.decodebytes(B)
is bytes; binary data with whatever encoding it has (text or image or ...). In this case, it is b'hello'
, which can be viewed as ascii-encoded text. To change to other encodings, first decode to unicode text and then encode to bytes in whatever other encoding you want. Most of the encodings you list above will have the same bytes.
>>> B=b"aGVsbG8="
>>> b = base64.decodebytes(B)
>>> b
b'hello'
>>> t = b.decode()
>>> t
'hello'
>>> t.encode('utf-8')
b'hello'
>>> t.encode('utf-16')
b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'
>>> t.encode('utf-32')
b'\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00'

Terry Jan Reedy
- 18,414
- 3
- 40
- 52