Search code examples
javascriptstringbase64concatenation

My base64 concatenated string has = characters. How to get rid of them


How should I concatenate base64 strings in order to get rid of the "=" characters ?

I sent a byte stream[] of data from the servlet as a http response, and at the client side I want to open the pdf viewer. But, I can't view it because of these extra characters.

I tried to concatenate with +=, with join, with concat, but I still have the = character at the end of each substring.

Maybe if there's a way to concat the strings without the last character.


Solution

  • The standard base-64 encoding encodes three bytes (3 * 8 bits) into 4 characters (4 * 6 bits). If the number of bytes in the original data is not divisible by 3, 2 = characters are added if the remainder was 1, and 1 = is added if the remainder was 2.

    Now, unfortunately you cannot concatenate 2 base-64 encoded strings if the first ends with padding characters = - you must decode both, concatenate the binary string*, and then re-encode, otherwise the latter part will be out of sync and all bytes of the second part will be decoded incorrectly.

    [*] it is not strictly necessary to re-encode the first part in its entirety but optimizing for that is not necessarily worthwhile.