Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 length calculation?

After reading the base64 wiki ...

I'm trying to figure out how's the formula working :

Given a string with length of n , the base64 length will be enter image description here

Which is : 4*Math.Ceiling(((double)s.Length/3)))

I already know that base64 length must be %4==0 to allow the decoder know what was the original text length.

The max number of padding for a sequence can be = or ==.

wiki :The number of output bytes per input byte is approximately 4 / 3 (33% overhead)

Question:

How does the information above settle with the output length enter image description here ?

like image 307
Royi Namir Avatar asked Nov 14 '12 12:11

Royi Namir


People also ask

How do you calculate the length of a Base64 string?

Each Base64 digit represents exactly 6 bits of data. So, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit Base64 digits (4×6 = 24 bits). This means that the Base64 version of a string or file will be at least 133% the size of its source (a ~33% increase).

How is Base64 image size calculated?

Base64 encodes 3 bytes of binary data on 4 characters. So to get the size of the original data, you juste have to multiply the stringLength (minus the header) by 3/4.

How many bytes is Base64?

Length of data Base64 uses 4 ascii characters to encode 24-bits (3 bytes) of data.

What is the maximum length of Base64 string?

The maximum length in 2732 characters. The result of the function is a varying length character string in CCSID 1208 that contains the bytes of character-string as a Base64-encoded string.


1 Answers

Each character is used to represent 6 bits (log2(64) = 6).

Therefore 4 chars are used to represent 4 * 6 = 24 bits = 3 bytes.

So you need 4*(n/3) chars to represent n bytes, and this needs to be rounded up to a multiple of 4.

The number of unused padding chars resulting from the rounding up to a multiple of 4 will obviously be 0, 1, 2 or 3.

like image 77
Paul R Avatar answered Oct 23 '22 12:10

Paul R