/** ***************************************** * Created by edonet@163.com * Created on 2019-03-29 17:50:31 ***************************************** * 转换前: xxxxxxxx, xxxxxxxx, xxxxxxxx * 转换后: 00xxxxxx, 00xxxxxx ,00xxxxxx, 00xxxxxx */ 'use strict'; /** ***************************************** * 加载依赖 ***************************************** */ import { Indexed } from './indexed'; import { utf8 } from './utf8'; /** ***************************************** * 定义编码映射表 ***************************************** */ const ch = new Indexed([ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' ]); /** ***************************************** * 抛出接口 ***************************************** */ export const base64 = { atob, btoa, encode, decode }; /** ***************************************** * 将base64解码成utf8字符串 ***************************************** */ export function atob(str: string): string { return utf8.decode(encode(str)); } /** ***************************************** * 将utf8字符串编码成base64 ***************************************** */ export function btoa(str: string): string { return decode(utf8.encode(str)); } /** ***************************************** * 编码字符 ***************************************** */ export function encode(str: string): number[] { let len = str.length, arr = [], i = 0; // 去除等号 while (str[len - 1] === '=') { len --; } // 转换字符 while (i < len) { let code = 0; // 获取编码 code = (code << 6) | (ch.indexOf(str[i ++]) & 0x3F); code = (code << 6) | (ch.indexOf(str[i ++]) & 0x3F); code = (code << 6) | (ch.indexOf(str[i ++]) & 0x3F); code = (code << 6) | (ch.indexOf(str[i ++]) & 0x3F); // 生成字符 arr.push(code >> 16 & 0xFF, code >> 8 & 0xFF, code & 0xFF); } // 去除多余字符 len < i -- && arr.pop(); len < i -- && arr.pop(); // 返回编码 return arr; } /** ***************************************** * 解码字符 ***************************************** */ export function decode(arr: ArrayLike, start = 0, end = arr.length): string { let data: string[] = [], eq = 3 - (end - start) % 3; // 转换编码 while (start < end) { let code = (arr[start ++] << 16) | (arr[start ++] << 8) | arr[start ++]; // 添加字符 data.push(ch.get(0x3F & code >> 18)); data.push(ch.get(0x3F & code >> 12)); data.push(ch.get(0x3F & code >> 6)); data.push(ch.get(0x3F & code)); } // 补全字符 if (eq < 3) { while(eq) { data[data.length - eq --] = '='; } } // 连接字符 return data.join(''); }