Reputation: 581
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
Reputation: 103263
Basically, yes. In basis, Base64 encodes 3 bytes using 4 characters. However, you must tackle 2 additional major issues:
=
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