Remove trailing “=” when base64 encoding

前端 未结 9 2047
时光取名叫无心
时光取名叫无心 2020-11-29 23:58

I am noticing that whenever I base64 encode a string, a \"=\" is appended at the end. Can I remove this character and then reliably decode it later by adding it back, or is

9条回答
  •  醉酒成梦
    2020-11-30 00:17

    The = is padding.

    Wikipedia says

    An additional pad character is allocated which may be used to force the encoded output into an integer multiple of 4 characters (or equivalently when the unencoded binary text is not a multiple of 3 bytes) ; these padding characters must then be discarded when decoding but still allow the calculation of the effective length of the unencoded text, when its input binary length would not be a multiple of 3 bytes (the last non-pad character is normally encoded so that the last 6-bit block it represents will be zero-padded on its least significant bits, at most two pad characters may occur at the end of the encoded stream).

    If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.
    Note that the data will not be valid Base64 in transport.

提交回复
热议问题