Hingle McJingleberry
Hingle McJingleberry

Reputation: 581

Java - Is there a way to determine file size from a base64 input?

We have a java program where the input is a base64 string version of the file. Files would be processed differently depending on their sizes so we have to find a way to determine its size based on its base64 input.

is there a way to do this? I'm thinking of recreating the file from the base64 then get the size but that would mean having to store it temporarily. We don't want that. Whats the best way to do this?

We are using Java 8

Upvotes: 0

Views: 2936

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103263

Basically, yes. In basis, Base64 encodes 3 bytes using 4 characters. However, you must tackle 2 additional major issues:

  • Base64 is sometimes split up into lines; the spec says whitespace is fine, and must be ignored. The 'new line' is one character (or sometimes two) that therefore must not be counted.
  • What if the file is not an exact multiple of 3? Base64 handles this using a padding algorithm. You always get the Base64 characters in sets of 4, but it is possible that the last set-of-4 encodes only 1 or 2 bytes instead of the usual 3. The = sign is used for padding.

Both of these issues can be addressed fairly easily:

It's not hard to loop over a string and increment a counter unless the character at that position in the string is whitespace.

Then multiply by 3 and divide by 4.

Then subtract 2 if the string ends in ==. If it ends in =, subtract 1.

You can count = signs during your loop.

int countBase64Size(String in) {
  int count = 0;
  int pad = 0;
  for (int i = 0; i < in.length(); i++) {
    char c = in.charAt(i);
    if (c == '=') pad++;
    if (!Character.isWhitespace(c)) count++;
  }
  return (count * 3 / 4) - pad;
}

Upvotes: 3

Related Questions