问题
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.
回答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 reencode the first part but optimizing for that still does not seem worthwhile.
回答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.
来源:https://stackoverflow.com/questions/29079702/my-base64-concatenated-string-has-characters-how-to-get-rid-of-them