Skip to content

Instantly share code, notes, and snippets.

@borismus
Created June 18, 2011 02:46
Show Gist options
  • Save borismus/1032746 to your computer and use it in GitHub Desktop.
Save borismus/1032746 to your computer and use it in GitHub Desktop.
Convert a base64 string into a binary Uint8 Array
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
@av01d
Copy link

av01d commented Jan 20, 2022

@7freaks-otte
Copy link

A note on the one-liners: While Uint8Array.from(atob(base64), (v) => v.charCodeAt(0)); really looks nice, I ran into memory issues on Chrome when converting a 200MB binary while the for-loop worked flawlessly

@OlegKorn
Copy link

OlegKorn commented Apr 2, 2025

Uncaught DOMException: String contains an invalid character
convertDataURIToBinary debugger eval code:6
downloadFile debugger eval code:17
debugger eval code:1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment