Skip to content

Instantly share code, notes, and snippets.

@carlos-jenkins
Created July 2, 2019 06:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlos-jenkins/3d28f9b05b5ae679ae5efe13d9cff9e8 to your computer and use it in GitHub Desktop.
Save carlos-jenkins/3d28f9b05b5ae679ae5efe13d9cff9e8 to your computer and use it in GitHub Desktop.
Calculate the length in bytes of a base64 string.
def b64len(b64str):
"""
Calculate the length in bytes of a base64 string.
This function could decode the base64 string to a binary blob and count its
number of bytes with len(). But, that's inefficient and requires more
memory that really needed.
Base64 encodes three bytes to four characters. Sometimes, padding is added
in the form of one or two '=' characters.
So, the following formula allows to know the number of bytes of a base64
string without decoding it::
(3 * (length_in_chars / 4)) - (number_of_padding_chars)
:param str b64str: A base64 encoded string.
:return: Length, in bytes, of the binary blob encoded in base64.
:rtype: int
"""
return (3 * (len(b64str) / 4)) - b64str[-2:].count('=')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment