Base64 encoding and decoding principles

Source: Internet
Author: User

The computer can only process numbers, so to process any text, you can only convert the text into numbers first.

Bit (BIT) (B) bit or bitIs the basis for computer operation and belongs to the binary category. Data transmission is mostly in the unit of [bit]. A single bit represents a 0 or 1 (that is, binary), and each eight digits constitute a byte.

Byte (B) bytesIs the basic unit of measurement for the file size in a computer. Data storage is measured in bytes. 1B = 8B. Therefore, the maximum number that a byte can express is 255 [11111111]

Encoding:

ASCII encoding: 1 byte. Therefore, only English numbers and symbols can be processed.

Unicode encoding: generally two bytes. It unified all languages into a set of encoding, so garbled code is solved, but the resulting result is a waste of storage space. For example, a large number of English characters in the text require two bytes of storage space for each character.

Utf8 encoding: utf8 combines the advantages and disadvantages of the two. It is a variable-length encoding method. It encodes a Unicode character into 1-6 bytes based on different numbers. The commonly used English letter is 1 byte, and the Chinese character is usually 3 bytes.

In computer memory, Unicode encoding is usually used. It is converted to utf8.

In pythonOrd () functionReturns the integer representation of a character.

Base64 encoding consists of 64 characters. The encoded characters are composed of the characters in the table. The specific process is as follows:

1) base64 encoding is grouped by the string length. Each 3 8-bit bytes are used as a group. If there are less than 3 bytes in a group, add 0. After encoding is completed, add =

2) Get the ASCII code of each character in each group

3) convert the ASCII code into an 8-bit binary code, that is, the length of each group is 3*8 = 24 characters.

4) divide the 24 bits into 4 6-bit bytes, and add 2 zeros before each 6-bit byte to re-form the 8-bit bytes.

5) convert the new 8-bit bytes into decimal format to find the corresponding base64 encoding table.

The Code is as follows (only English conversion is supported below ):

Import string

Base64_char = string. ascii_uppercase + String. ascii_lowercase + String. digits + '+/' # base64 encoding table

Def decode (s ):

Num = 0 if (3-len (s) % 3) = 3 else (3-len (s) % 3) # The number of groups to be supplemented is insufficient.

New_s = ["{: 0> 8 }". format (Bin (ord (I )). replace ("0b", "") for I in S] # convert a string to a binary string of 8

New_s = "". Join ([new_s.append ("0" * 8) for X in range (Num)]) # for less than three groups, add 0

Num1 = int (new_s/6) # number of groups that can be divided by 6 digits

New_s = ["{: 0> 8 }". format (new_s [I * 6 :( I + 1) * 6]) for I in range (num1)] # Add the new group to 8 bits

New_s = [int (x, 2) for X in new_s] # convert the new binary into a 10-digit system.

Result = ". Join ([base64_char [I] For I in new_s]) +" = "* num # Check the encoding table and complete =

Print (result)

  

Corresponding decoding, that is, reverse execution of the above function:

Def decode (s ):

While s [-2:-1] = "= ":

S = S. Replace ("=", "") # Remove the = sign.

S1 = ["{: 0> 6 }". format (Bin (base64_char.index (x )). replace ("0b", "") for X in S] # Find the encoding table, locate the corresponding location, and convert it to binary

S1 = "". Join (S1)

Num = Len (S1) // 8 # calculate the number of groups

S2 = [S1 [x * 8 :( x + 1) * 8] for X in range (Num)] # convert to 8-bit bytes

S2 = [CHR(INT (S1 [Index], 2) for index in range (Num)]

Result = "". Join (S2)

Print (result)

    

Base64 encoding and decoding principles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.