I'm trying to predict the size string representation of a base64 encoded byte array.
I've come up with the formula below, however the length of the actual encodedString
is 4 larger than the base64EncodedSize
.
The whole idea here is to calculate/predict what the encoded string size would be for a given byte[]
. I would prefer not to convert the byte[
] to a base 64 string just to determine it's length.
FileInfo pdfFile = new FileInfo(@"C:\TEMP\1.pdf");
long originalSizeInBytes = pdfFile.Length;
String encodedString = Convert.ToBase64String(File.ReadAllBytes(pdfFile.FullName));
long base64EncodedSize = (originalSizeInBytes / 3) * 4;
----------------------------------------------------------------------------------
- Results -
-----------------------------------------------------------------------------------
originalSizeInBytes 913663 long
base64EncodedSize 1218216 long
encodedString.Length 1218220 int
base64EncodedSize 1218216 long
encodedString.Length - base64EncodedSize 4 long
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.
Length of data Base64 uses 4 ascii characters to encode 24-bits (3 bytes) of data.
Hex. BASE64 characters are 6 bits in length. They are formed by taking a block of three octets to form a 24-bit string, which is converted into four BASE64 characters.
Very roughly, the final size of Base64-encoded binary data is equal to 1.37 times the original data size + 814 bytes (for headers). You can use ContentLength property of the request to determine what the size is in bytes, although if you are uploading more then one image, it might be trickier.
That will be
long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With