16进制数转base64方法(atob和btoa方法不能使用情况下)

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;
}

本文用于备忘和分享

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值