2

I've read following topic and found this formula there:

length = 4*(n/3)

I started to test it:

1 symbol: Base64.getEncoder().encodeToString("1".getBytes()) =>MQ==(4 symbols)

2 symbols: Base64.getEncoder().encodeToString("12".getBytes()) =>MTI= (4 symbols)

5 symbols: Base64.getEncoder().encodeToString("12345".getBytes()) =>MTIzNDU=(8 symbols)

8 symbols: Base64.getEncoder().encodeToString("12345678".getBytes()) =>MTIzNDU2Nzg=(12 symbols)

21symbols: Base64.getEncoder().encodeToString("123456789012345678901".getBytes()) => MTIzNDU2Nzg5MDEyMzQ1Njc4OTAx (28 symbols)

Looks like this formula doesn't work.

Can you please explain mu results?

Community
  • 1
  • 1
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

4

With 64 digits (26) one digit can represent 6 bits. Hence 4 digits can represent exactly 4*6 bits = 3 bytes.

(Using ÷ for explicit integer division:)

With n bytes, 4*(n÷3) digits are needed plus for the remainder n%3 (0 < 3 bytes) there is a need for 0 upto 4 digits:

0 bytes (0 bits)    0 digits
1 byte  (8 bits)    2 digits (12 bits)     + "=="
2 bytes (16 bits)   3 digits (18 bits)     + "="

Often there is a padding upto 4 digits/padding chars, using =. This cannot be 0 as one then would add a byte 0x0.

Then the formula is 4 * Math.ceil(n / 3.0).

Without padding: Math.ceil(n * 8 / 6.0) = Math.ceil(n * 4 / 3.0) = (n * 4 + (3 - 1)) ÷ 3.

In java one should use int division only:

int base64Length(byte[] b) {
    int n = b.length;
    return (n * 4 + 2)/3;
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
-2

Try length = 4*((n/3) + 1), where "/" is integer division.

Edit: Lexicore is correct, my formula fails when the remainder is zero.

int length = 4 * (n / 3);
if (n % 3 > 0) length++;
Steve11235
  • 2,849
  • 1
  • 17
  • 18