The base64.b4()
function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.
The base64.b64decode()
function takes s
as the only mandatory parameter.
s
contains a byte-like object that is to be decoded.altchars
parameter specifies the alternative characters encoded instead of +
or /
characters. altchars
is a byte-like object and must have a minimum length of 2.validate
parameter is False
, the function will discard all non-base64 or non-alternative characters in s
; otherwise, it raises the binascii.Error
exception.Note: The
base64.b64encode()
function encodes 3 bytes at a time. If the last set of bytes contains less than 3 bytes, its encoding is padded with the=
character. One=
character means the last set contains two bytes, and two=
characters mean the last set contains a single byte.
The following code demonstrates how to decode a byte-like object in base64
without alternative characters.
pppfoo???
through the utf-8
encoding.base64.b64decode()
function.import base64#string to encodestring = 'pppfoo???'#convert string to bytesstring_encode = string.encode('utf-8')#ecode in base 64encoded = base64.b64encode(string_encode)#display encode dataprint(encoded)#decode from base 64decoded = base64.b64decode(encoded)#convert from bytes to string and displayprint(decoded.decode('utf-8'))
The following program demonstrates how to decode a byte-like object in base64 with alternative characters.
pppfoo???
through the utf-8
encoding.altchars
argument that /
or +
is to be encoded with :
.base64.b64decode()
function. The altchars
parameter is input to specify that /
or +
is encoded as :
.If the program does not specify the
altchars
parameter while decoding, abinascii.Error
exception will be thrown, as:
does not belong to the normal base64 alphabets.
import base64#string to encodestring = 'pppfoo???'#convert string to bytesstring_encode = string.encode('utf-8')#ecode in base 64encoded = base64.b64encode(string_encode, altchars=b'-:')#display encode dataprint(encoded)#decode from base 64decoded = base64.b64decode(encoded, altchars=b'-:')#convert from bytes to string and displayprint(decoded.decode('utf-8'))
If the padding of the encoded data is incorrect, the program throws a
binascii.Error
exception.