手写一个base64解码的方法

在前端开发中,虽然我们可以直接使用浏览器提供的 atob 函数来进行 Base64 解码,但如果你想要手写一个 Base64 解码的方法,以下是一个简单的实现:

function base64Decode(input) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    let str = '';
    let byte, enum1, enum2, enum3, enum4;

    for (let i = 0; i < input.length;) {
        enum1 = chars.indexOf(input.charAt(i++));
        enum2 = chars.indexOf(input.charAt(i++));
        enum3 = chars.indexOf(input.charAt(i++));
        enum4 = chars.indexOf(input.charAt(i++));

        byte = (enum1 << 2) | (enum2 >> 4);
        str += String.fromCharCode(byte);

        if (enum3 !== 64) {
            byte = ((enum2 & 15) << 4) | (enum3 >> 2);
            str += String.fromCharCode(byte);
        }

        if (enum4 !== 64) {
            byte = ((enum3 & 3) << 6) | enum4;
            str += String.fromCharCode(byte);
        }
    }

    return str;
}

// 使用示例:
const encodedString = 'SGVsbG8gd29ybGQ='; // "Hello world" 的 Base64 编码
const decodedString = base64Decode(encodedString);
console.log(decodedString); // 输出 "Hello world"

这个 base64Decode 函数接受一个 Base64 编码的字符串作为输入,并返回解码后的字符串。它首先定义了一个包含所有可能的 Base64 字符的字符串 chars。然后,它遍历输入字符串,每次取出 4 个字符,并将这些字符转换为它们在 chars 中的索引。这些索引被用来计算原始字节,并通过 String.fromCharCode 转换为字符串。注意,Base64 编码中的 = 字符用于填充,当遇到它时,我们可以停止处理当前的 4 字符组。

posted @ 2024-12-22 09:32  王铁柱6  阅读(8)  评论(0编辑  收藏  举报