Skip to content Skip to sidebar Skip to footer

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 wan

Solution 1:

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.

Solution 2:

I'm not sure I do understand your question, but for me it sounds like you want to concatenate multiple Base64-encoded strings and then decode them. This won't work regardless of the =-characters.

For example take a look at the following Base64-encodings:

X20    -> IA==
X20 20-> ICA=

But concatenating IAIA and decoding it will result in X 20 02 00.

The reason why it can't work is that each character in Base64-coded form may represent parts from more than one unencoded byte and each unencoded byte might be represented in more than one Base64-character.

So as Antti Haapala correctly stated: you have to decode first and then conactenate the output instead of vice versa.

Post a Comment for "My Base64 Concatenated String Has = Characters. How To Get Rid Of Them"