In the development, we sometimes need to Base64 encoding for a string. For example, in the network transmission, the data uses SCII encoding and some special characters cannot be parsed by the protocol. Therefore, after Base64 encryption, the data is transmitted.

Any string encrypted by Base64 contains only the a-z a-z 0-9 + / part and the ending =

1 Converts the string to a byte array to get 10 bytes.

2 converts base 10 to base 2

3 If base 10 is negative, find the corresponding base 2 of the integer, take the inverse, +1

4 If the number of binary digits is less than 8, add 0 before it

5 Groups bytes by six bits

If 7 is less than 6 bits, add 8 bytes of 0

8 Convert the intercepted 2-byte to 10-byte

In base 9 and 10, the following table is the result of encoding.

Public static void a() throws Exception {String s = "I am Chinese "; byte[] encode = Base64.getEncoder().encode(s.getBytes("UTF-8")); String s1 = new String(encode,"UTF-8"); System.out.println(s1); //5oiR5piv5Lit5Zu95Lq6 byte[] decode = Base64.getDecoder().decode(s1.getBytes("UTF-8")); String s2 = new String(decode,"UTF-8"); System.out.println(s2); // I am Chinese}Copy the code

View Code

I'm Chinese corresponding decimal byte - 26-120-111-26-104-81, to 28, 72, 83, 27, 101, 67, - 28-70-70, because it is negative, Therefore, the negative +1 operation is required. -26 00011010 11100101 11100110-120 01111000 10000111 10001000-111 01101111 10010000 10010001-26 00011010 11100101 11100110-104 01101000 10010111 10011000-81 01010001 10101110 10101111-28 00011100 11100011 11100100-72 01001000 10110111 10111000-83 01010011 10101100 10101101-27 00011011 11100100 11100101-101 01100101 10011010 10011011 -67 01000011 10111100 10111101-28 00011100 11100011 11100100-70 01000110 10111001 10111010-70 01000110 10111001 10111010Copy the code

View Code

Divide into groups of six, switch to base 10, Check the code table 111001 101000 100010 010001 111001 101001 100010 101111 111001 001011 100010 101101 111001 011001 101110 111101 111001 001011 101010 111010 57 40 34 18 57 41 34 47 57 11 34 37 57 25 46 61 57 11 42 58 5 o i R 5 p i v 5 L i t 5 Z u 9 5 L q 6Copy the code

View Code

Finally, some string conversions have the character 5oiR5piv5Lit5Zu95Lq6MQ==, which means less than 6 bytes were truncated, and an = sign means one byte was added, which is eight zeros

Appendix a base conversion tool for the site

tool.oschina.net/hexconvert/