Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

后端 未结 10 2080
野趣味
野趣味 2020-11-22 16:24

I\'m using the Javascript window.atob() function to decode a base64-encoded string (specifically the base64-encoded content from the GitHub API). Problem is I\'

10条回答
  •  耶瑟儿~
    2020-11-22 16:53

    If treating strings as bytes is more your thing, you can use the following functions

    function u_atob(ascii) {
        return Uint8Array.from(atob(ascii), c => c.charCodeAt(0));
    }
    
    function u_btoa(buffer) {
        var binary = [];
        var bytes = new Uint8Array(buffer);
        for (var i = 0, il = bytes.byteLength; i < il; i++) {
            binary.push(String.fromCharCode(bytes[i]));
        }
        return btoa(binary.join(''));
    }
    
    
    // example, it works also with astral plane characters such as '

提交回复
热议问题