/** ***************************************** * 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'; /** ***************************************** * 定义编码映射表 ***************************************** */ const ch = new Indexed( ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'], { 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15 } ); /** ***************************************** * 抛出接口 ***************************************** */ export const hex = { encode, decode }; /** ***************************************** * 编码字符 ***************************************** */ export function encode(str: string): number[] { let len = str.length, arr = [], i = 0; // 转换字符 while (i < len) { let code = 0; // 获取编码 code = (code << 4) | (ch.indexOf(str[i ++]) & 0x0F); code = (code << 4) | (ch.indexOf(str[i ++]) & 0x0F); // 生成字符 arr.push(code); } // 返回编码 return arr; } /** ***************************************** * 解码字符 ***************************************** */ export function decode(arr: ArrayLike, start = 0, end = arr.length): string { let data: string[] = []; // 转换编码 while (start < end) { let code = arr[start ++]; // 添加字符 data.push(ch.get(code >> 4), ch.get(code & 0x0F)); } // 连接字符 return data.join(''); }