het.oosten
het.oosten

Reputation: 885

Decode base64 string without newline character

I am working with some base64 data. The expected output is 6 hex numbers like in the first example. However sometimes I get a newline character like in the second example (with 5 hex values)

base64.b64decode('DAAI9BTT')
b'\x0c\x00\x08\xf4\x14\xd3'
base64.b64decode('DAAKRRTT')
b'\x0c\x00\nE\x14\xd3'

I suspect I get the value 0A and this is converted to newline. When I trim the newline I miss a hex value

Upvotes: 2

Views: 569

Answers (1)

pho
pho

Reputation: 25479

The \n just comes from the string representation of the bytearray from __repr__. Extract the contents of the byte array into a list, and you get what you expect:

[p for p in base64.b64decode('DAAKRRTT')]
# Output: [12, 0, 10, 69, 20, 211]

Or, in hex:

[hex(p) for p in base64.b64decode('DAAKRRTT')]
# Output: ['0xc', '0x0', '0xa', '0x45', '0x14', '0xd3']

Upvotes: 3

Related Questions