Decode Base64 string to byte array
<p>I would create a python script that decode a Base64 string to an array of byte (or array of Hex values).</p>

<p>The embedded side of my project is a micro controller that creates a base64 string starting from raw byte. The string contains some no-printable characters (for this reason I choose base64 encoding).</p>

<p>On the Pc side I need to decode the the base64 string and recover the original raw bytes.</p>

<p>My script uses python 2.7 and the base64 library:</p>

<pre><code>base64Packet = raw_input('Base64 stream:')

packet = base64.b64decode(base64Packet )

sys.stdout.write("Decoded packet: %s"%packet)
</code></pre>

<p>The resulting string is a characters string that contains some not printable char.</p>

<p>Is there a way to decode base64 string to byte (or hex) values?</p>

<p>Thanks in advance!</p>

<p>You can use <a href="https://docs.python.org/2/library/functions.html#bytearray" rel="nofollow">bytearray</a> for exactly this. Possibly the <a href="https://docs.python.org/2/library/binascii.html" rel="nofollow">binascii</a> module and <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">struct</a> can be helpful, too.</p>

<pre><code>import binascii
import struct

binstr=b"thisisunreadablebytes"

encoded=binascii.b2a_base64(binstr)
print encoded
print binascii.a2b_base64(encoded)

ba=bytearray(binstr)
print list(ba)

print binascii.b2a_hex(binstr)
print struct.unpack("21B",binstr)
</code></pre>

python string embedded base64 decode