如何计算Base64编码字符串的长度?公式验证测试解析
Base64 Encoded String Length: Formula & Practical Test Results
Hey everyone,
I recently looked into calculating the length of Base64-encoded strings and came across this handy formula that matches real-world behavior perfectly:length = 4 * ceil(n / 3)
(Where n is the number of bytes in your original input string)
To confirm this, I ran several tests using Java's built-in Base64 encoder. Here's what I found:
- 1 character input (
"1")- Code used:
Base64.getEncoder().encodeToString("1".getBytes()) - Encoded output:
MQ==→ 4 characters total
- Code used:
- 2 characters input (
"12")- Code used:
Base64.getEncoder().encodeToString("12".getBytes()) - Encoded output:
MTI=→ 4 characters total
- Code used:
- 5 characters input (
"12345")- Code used:
Base64.getEncoder().encodeToString("12345".getBytes()) - Encoded output:
MTIzNDU=→ 8 characters total
- Code used:
- 8 characters input (
"12345678")- Code used:
Base64.getEncoder().encodeToString("12345678".getBytes()) - Encoded output:
MTIzNDU2Nzg=→ 12 characters total
- Code used:
The core logic here is that Base64 converts every 3 input bytes into 4 encoded characters. If the input byte count isn't a multiple of 3, padding characters (=) are added to make the final length a multiple of 4—this is why we use the ceiling of n/3 in the formula to account for partial byte chunks.
内容的提问来源于stack exchange,提问作者gstackoverflow
相关产品推荐
相关产品推荐

