赞
踩
此功能需要在小程序中实现,无法使用一些现成的函数btoa,Uint8Array等
// 将字符串编码为 Uint8Array export const encodeString = (str) => { var utf8Array = []; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i); // 获得字符的ASCII if (charCode < 0x80) { utf8Array.push(charCode); } else if (charCode < 0x800) { utf8Array.push(0xc0 | (charCode >> 6)); utf8Array.push(0x80 | (charCode & 0x3f)); } else if (charCode < 0x10000) { utf8Array.push(0xe0 | (charCode >> 12)); utf8Array.push(0x80 | ((charCode >> 6) & 0x3f)); utf8Array.push(0x80 | (charCode & 0x3f)); } else { utf8Array.push(0xf0 | (charCode >> 18)); utf8Array.push(0x80 | ((charCode >> 12) & 0x3f)); utf8Array.push(0x80 | ((charCode >> 6) & 0x3f)); utf8Array.push(0x80 | (charCode & 0x3f)); } } return new Uint8Array(utf8Array); } // 字符串转为base64 export const base64Encode = (inputString) => { const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/="; let inputBytes = encodeString(inputString); let output = ""; let chr1, chr2, chr3, enc1, enc2, enc3, enc4; let i = 0; while (i < inputBytes.length) { chr1 = inputBytes[i++]; chr2 = inputBytes[i++]; chr3 = inputBytes[i++]; enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。