简体   繁体   中英

Encode then decoded in base64 doesn't output my input arraybuffer

Given the two functions below that I use to encode and decode in base64. If I encode then decode, I just do this, then I don't get the same values between my ouput and my input.

Any idea what I'm doing wrong ?

function _base64ToArrayBuffer(string_base64)    {
    var binary_string =  window.atob(string_base64);
    var len = binary_string.length;
    var bytes = new Uint8Array( len );
    for (var i = 0; i < len; i++)        {
        var ascii = string_base64.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes.buffer;
}

function _arrayBufferToBase64( array_buffer )    {
    var binary = '';
    var bytes = new Uint8Array( array_buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++)        {
        binary += String.fromCharCode( bytes[ i ] )
    }
    return window.btoa( binary );
}



var input = my_ArrayBuffer;
var raw_data_base64 = _arrayBufferToBase64(input);
var ouput = _base64ToArrayBuffer(raw_data_base64);

Your line number 6

var ascii = string_base64.charCodeAt(i);

should be

var ascii = binary_string.charCodeAt(i);

Your problem is in _base64ToArrayBuffer

for (var i = 0; i < len; i++) {
    var ascii = string_base64.charCodeAt(i); // THIS LINE
    bytes[i] = ascii;
}

If you think about what the ArrayBuffer you're getting back actually means (in terms of charcodes) it was giving you back your Base64 String .

Looks like you actually wanted to use

binary_string.charCodeAt(i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM