Last active
June 25, 2019 21:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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