Convert Between Bytes and a Base64 String

#codesnippet #javascript

function base64ToArrayBuffer(base64) {
    const binaryString = globalThis.atob(base64);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}

function arrayBufferToBase64( buffer ) {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    for (let i = 0; i < bytes.byteLength; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return globalThis.btoa(binary);
}

Tests

// Should output the inner array there
console.log(new Uint8Array(base64ToArrayBuffer(arrayBufferToBase64((new Uint8Array([255, 2, 99])).buffer))))

// Should output the inner base64 there
console.log(arrayBufferToBase64(base64ToArrayBuffer('SGV5IHRoZXJlLCBpdCdzIHdvcmtpbmc=')))