JS Base64 turn Binary

Source: Internet
Author: User

Base64 Coding Rules

1. Turn 3 characters into 4 characters.
2, every 76 characters multibyte a newline character.
3, the last Terminator also to deal with.
Conversion before 11111101, 11111111, 11111111 (binary)
Converted 00111111, 00011111, 00111111, 00111111 (binary, because the base64 only need 6 bits to be satisfied, but a byte is 8 bits, so more than 2 useless 0)

To go back to 2, you need to cut the front 00 and let the data come up.

The first approach: using ToString (2) to convert to 2 binary strings, and then splicing, but the binary data too much, the direct operation of memory is much faster, so the string is no longer used.

A second approach:

Base64 encoded Table Const MAP = {"0": 1, "2":, "3": +, "4": "5":, "6": "7": 8 ":," 9 "," A ": 0 , "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": Ten, "L": One, "M": A, "N": "O": "P"  :, "Q": +, "R": +, "S": +, "T": +, "U": +, "V": +, "W": "X": +, "Y":, "Z": +, "a": +, "B":, "C": 28,  "D": "E": +, "F": +, "G": +, "H": "I":, "J": +, "K": +, "L": Panax Notoginseng, "M": Max, "n": G, "O": +, "P": KT, "Q": "R": A, "s": "," "T": "G", "U": +, "V": +, "w": ×, "X": $, "y": +, "Z": Wuyi, "+": +, "/":}function Base64to2 (base64) {Let Len = base64.length *. 75//Convert to Int8array required length base64 = Base64.replace (/=*$/, ")//Remove = (placeholder) Const INT8 =    New Int8array (LEN)//Set Int8array view let arr1, ARR2, ARR3, ARR4, p = 0for (Let i = 0; i < base64.length; i + = 4) { ARR1 = Map[base64[i]]//each cycle converts base644 bytes to 3 int8array Direct ARR2 = Map[base64[i + 1]] Arr3 = Map[base64[i + 2]] ar R4 = Map[base64[i + 3]] Suppose data arr data 00101011 00101111 00110011 00110001 int8[p++] = arr1 << 2 | ARR2 >> 4//upper action arr1 move left 2 bits to 10101100//ARR2 to right 4 bits: 00000010//| For ' and ' Operation: 10101110 int8[p++] = arr2 << 4 | ARR3 >> 2 int8[p++] = ARR3 << 6 | ARR4} return int8}

  

JS Base64 turn Binary

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.