1 const charsMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); 2 3 function binaryToBase64(chars) { 4 const padLength = 3 - chars.length % 3; 5 return (chars.split('').map(char => { 6 return char.charCodeAt(0).toString(2).padStart(8, '0'); 7 }).join('') + '0'.repeat(2 * padLength)).split(/\B(?=(?:\d{6})+$)/g).map(char => { 8 return charsMap[+('0b' + char)]; 9 }).join('') + '='.repeat(padLength); 10 } 11 12 function base64ToBinary(base64) { 13 const tail = base64.match(/=+/); 14 const padLength = tail ? tail[0].length : 0; 15 return base64.slice(0, -padLength).split('').map(char => { 16 return charsMap.indexOf(char).toString(2).padStart(6, '0'); 17 }).join('').slice(0, -padLength * 2).split(/\B(?=(?:\d{8})+$)/g).map(code => { 18 return String.fromCharCode(+('0b' + code)); 19 }).join(''); 20 } 21 22 export { 23 binaryToBase64, 24 base64ToBinary 25 }
标签:binary,return,base64,padLength,char,split,const From: https://www.cnblogs.com/aurora-power/p/17600478.html