MacNilly
MacNilly

Reputation: 137

Base 64 decode from raw binary

I am trying to decode base64 from raw binary:

As input, I have 4 6-bit values

010000 001010 000000 011001

which I convert to decimal, giving

16 10 0 25

and finally decode using the base 64 table, giving

Q K A Z

This is verified to be the correct result.

I would like to use Python's base64 module to automate this, but using

import base64
base64.b64decode( bytearray([16,10,0,25]) )

returns an empty string.

What is the proper way to use this library with the given inputs?

Upvotes: 0

Views: 595

Answers (1)

senshin
senshin

Reputation: 10360

[16, 10, 0, 25] isn't a base64 string, really; I don't think base64 has any functions for converting numeric representations of the base64 alphabet to their alphabetic representations. It's not difficult to roll your own, though:

def to_characters(numeric_arr):
    target = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + b'abcdefghijklmnopqrstuvwxyz' + b'0123456789' + b'+/'
    return bytes(target[n] for n in numeric_arr)

Then:

>>> to_characters(bytearray([16, 10, 0, 25]))
b'QKAZ'
>>> to_characters([16, 10, 0, 25]) # <- or just this
b'QKAZ'

You can now pass this bytes object to base64.b64decode:

>>> base64.b64decode(b'QKAZ')
b'@\xa0\x19'

(Note that you had a syntax issue in your example use of bytearray - don't do bytearray[...]; do bytearray([...]). Python doesn't use C-like int array[size] syntax.)

Upvotes: 1

Related Questions