Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predict the byte size of a base64 encoded byte[]

Tags:

c#

base64

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
like image 961
Michael G Avatar asked Mar 12 '12 14:03

Michael G


People also ask

How do I find the size of a Base64 file?

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 a Base64 character?

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

How long is a 64 byte string?

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.

How big is a Base64 encoded image?

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.


1 Answers

That will be

long base64EncodedSize = 4 * (int)Math.Ceiling(originalSizeInBytes / 3.0);
like image 172
Anton Gogolev Avatar answered Sep 27 '22 22:09

Anton Gogolev