atob和btoa方法不能使用情况下使用如下代码进行16进制和base64间的转换
function hexToBase64(hexString) {
const base64Chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// 将16进制字符串转换为字节数组
const bytes = [];
for (let i = 0; i < hexString.length; i += 2) {
bytes.push(parseInt(hexString.substr(i, 2), 16));
}
let base64String = '';
let remainder = 0;
let remainderLength = 0;
for (let i = 0; i < bytes.length; i++) {
remainder = (remainder << 8) + bytes[i];
remainderLength += 8;
while (remainderLength >= 6) {
base64String += base64Chars.charAt((remainder >>> (remainderLength - 6)) & 0x3F);
remainderLength -= 6;
}
}
if (remainderLength > 0) {
remainder <<= (6 - remainderLength);
base64String += base64Chars.charAt(remainder & 0x3F);
}
// 补足Base64字符串的长度为4的倍数
while (base64String.length % 4 !== 0) {
base64String += '=';
}
return base64String;
}
function base64ToHexStr(base64String) {
// 手动解码 Base64 字符串
const base64Chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const base64Decoded = [];
for (let i = 0; i < base64String.length;) {
let enc1 = base64Chars.indexOf(base64String.charAt(i++));
let enc2 = base64Chars.indexOf(base64String.charAt(i++));
let enc3 = base64Chars.indexOf(base64String.charAt(i++));
let enc4 = base64Chars.indexOf(base64String.charAt(i++));
let chr1 = (enc1 << 2) | (enc2 >> 4);
let chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
let chr3 = ((enc3 & 3) << 6) | enc4;
base64Decoded.push(chr1);
if (enc3 !== 64) base64Decoded.push(chr2);
if (enc4 !== 64) base64Decoded.push(chr3);
}
// 将解码后的字符转换为 16 进制字符串
let hexString = '';
for (let i = 0; i < base64Decoded.length; i++) {
const hexCharCode = base64Decoded[i].toString(16);
hexString += ('0' + hexCharCode).slice(-2);
}
return hexString;
}
本文用于备忘和分享