Why do some codes need to be encoded in base64?

  javascript, question

I don’t think this is encryption, because base64 is reversible, so it is not encryption.
Therefore, what is the purpose of encoding with base64?

Base64 is mainly used to convert non-printable characters into printable characters, or simply to encode binary data into ASCII characters.

The main purpose of encoding binary data into ASCII characters is to insert binary data into plain text content. Common application scenarios include:

  1. E-mail

    This can be referred toRuan Yifeng’s MIME Notes

  2. Microsoft’s MHT format

    This is a format that imitates the mail format and packs multiple resources into one file. All binary resources are Base64 encoded.

  3. XML file

    This is a plain text file. If you want to design a data format based on XML format that can store pictures or other attachments, you need to transcode these binary data into ASCII characters.

  4. DATA URL

    Recently popularData URL, to use binary data in URL, of course, can only be ASCII coding

Of course, besides Base64, there are other encoding methods that can encode binary data into ASCII characters, such as Hex number system, besides which there are Quoted-printable, etc. Even the way the percentage XX is used in the URL to encode non-ASCII characters can be counted.

Of course, in general non-specific environments, Hex number system and Base64 codes are often used, mainly because these two codes are easy to use and the amount of converted data is relatively small.

Hex number system is a generalOneBytes encoded into2.Hexadecimal characters, such as0x10110110Code intoB6After conversion, the amount of data will increase1 times.

Base64 encoding is to3.Bytes total24Bit data, per6.Bits a Base64 character[0-9a-zA-Z plus/]Indicates that,24Bit data required in total4.Base64 characters indicate that the encoded data has increased by about1/3. Why is “about”? Because if the number of bytes of the original data is not a multiple of 3, the bits need to be filled, so the amount of data converted will be larger than the original4/3A little more.

From the above data growth ratio, Base64 encoding saves more disk capacity than Hex number system, so generally larger data need to be ASCII encoded using Base64; For smaller data, hexadecimal (which can be decoded with a pen and paper) is easily recognized manually.