base64
Base64 is one of the most common encoding methods for transmitting 8Bit bytecode on the network. Base64 is a method to represent binary data based on 64 printable characters.
For the front end, you can use Base64 instead wherever you can put paths.
The buffer object in node can be output as base64 by toString(‘base64’). Here is a brief description of how Chinese characters are converted into Base64.
For example, let’s explore how a man “ha” can be converted from base64 to “5ZOI”.
First we convert the man to Buffer using the from method of the Buffer object in NodeJS. You get three hexadecimal bytes e5, 93, 88. You can see that this functor is made up of three bytes.
const buf = Buffer.from("Hello");
console.log(buf); // // e5 93 88
Copy the code
We then convert each byte to binary, 0x for hexadecimal, we need to spell 0x before e5, 93, 88, and in toString we can pass in the hexadecimal that we want to convert, 2 here.
// Convert each byte to binary
(0xe5).toString(2); / / 11100101
(0x93).toString(2); / / 10010011
(0x88).toString(2); / / 10001000
Copy the code
Then join the three resulting binary data together to get 111001011001001110001000.
111001011001001110001000
Copy the code
Then cut 111001011001001110001000 in groups of six, which can be cut into 4 parts.
111001 011001 001110 001000
Copy the code
Then the zeros are added to the front of each group to make 8 bits.
00111001
00011001
00001110
00001000
Copy the code
The four sets of data obtained are respectively converted to base 10 data. There are four digits in total, so isn’t that close to the four characters you get when you convert the word “ha” to base64?
parseInt('00111001'.2); // Binary changes to base 10 57
parseInt('00011001'.2); // Change the binary to base 10
parseInt('00001110'.2); // Binary changes to base 10 14
parseInt('00001000'.2); // Change binary to base 10 8
Copy the code
The base64 encoding data is basically obtained from a-z plus a-z plus 0123456789+/. Let’s concatenate this string.
/ / base64 encoding
let str = 'ABCDEFGHIGKLMNOPQRSTUVWSYZ';
str += str.toLowerCase(); // Concatenate lowercase characters once
str += '0123456789 + /'; // Add the numbers once
Copy the code
We know that strings can be used like arrays to retrieve characters at specified positions by subscript. In this case, the characters at the corresponding positions are obtained by the decimal conversion above: 5 for 57, Z for 25, O for 14, and I for 8.
Splicing these four characters together makes 5ZOI. That’s base64 after the conversion.
const base64 = str[57] + str[25] + str[14] + str[8]; // 5ZOI
Copy the code
Base64 translation steps
1. Pass the string to buffer. from, and convert each 16 Buffer bytes in the Buffer to base 2
2. Splice all binaries together, divide them into groups of 6, add 00 in front of them, and make up 8-bit binaries
3. Convert the new binary to base 10
4. In base64 set, they are taken out by base 10 subscript and linked