Created
July 2, 2019 06:39
-
-
Save carlos-jenkins/3d28f9b05b5ae679ae5efe13d9cff9e8 to your computer and use it in GitHub Desktop.
Calculate the length in bytes of a base64 string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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