I was in need to calculate the size of the output of Base64.strict_encode64.
I wanted to get this value to determine if the file was too big to send to an API endpoint.
If the file was too big I didn’t want to spend time processing and trying to send the data.
So I put together this method using a bunch of answers from stack overflow and the article in wikipedia for base64
My method looks like this:
def calculate_strict_base64_size(path) # get the size of the file size = File.size(path) # calculate the code size, # see this post # http://stackoverflow.com/questions/13378815/base64-length-calculation code_size = (size * 4) / 3 # add any needed padding 0, 1, 2 # see this post for the padding calculation # http://stackoverflow.com/questions/1533113/calculate-the-size-to-a-base-64-encoded-message # strict_encode64 complies with RFC 4648 and no line feeds are added # so we only need the padding padding = (size % 3)? (3 - (size % 3)) : 0 # combine for the totals plus terminating null character total_size = code_size + padding + 1 return total_size end
and for short:
def calculate_strict_base64_size(path) size = File.size(path) code_size = (size * 4) / 3 padding = (size % 3)? (3 - (size % 3)) : 0 total_size = code_size + padding + 1 return total_size end
Leave a Reply