Skip to content

Instantly share code, notes, and snippets.

@kvangrae
Last active June 25, 2019 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kvangrae/742fdc2c67d308ce5cb3ef25f06ac31d to your computer and use it in GitHub Desktop.
Save kvangrae/742fdc2c67d308ce5cb3ef25f06ac31d to your computer and use it in GitHub Desktop.
Computes the expected decoded byte size of the Base64 encoded data. Reference: https://tools.ietf.org/html/rfc4648
import static java.util.Objects.requireNonNull;
public class Base64Util {
private static final double BASE64_SIZE_RATIO = 4.0d / 3;
private Base64Util() {
}
/**
* Computes the expected decoded byte size of the base64 encoded data.
* <p>
* NOTE: This code assumes it is being passed a valid base64 encoded string.
*
* @param base64Text valid base64 encoded text
* @return expected decoded byte size
*/
public static int computeDecodedByteSize(String base64Text) {
return (int) (trueLength(requireNonNull(base64Text)) / BASE64_SIZE_RATIO);
}
private static int trueLength(String base64Text) {
return base64Text.length() - lineFeedsAndPaddingCount(base64Text);
}
private static int lineFeedsAndPaddingCount(String base64Text) {
return (int) base64Text.chars().filter(c -> c == '\n' || c == '\r' || c == '=').count();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment