Skip to content

Instantly share code, notes, and snippets.

@sketchpunk
Created September 1, 2017 03:08
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchpunk/f5fa58a56dcfe6168a9328e7c32a4fd4 to your computer and use it in GitHub Desktop.
Save sketchpunk/f5fa58a56dcfe6168a9328e7c32a4fd4 to your computer and use it in GitHub Desktop.
Base64 String to Float32Array in Javascript, good for WebGL
var blob = window.atob("AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAA"), // Base64 string converted to a char array
fLen = blob.length / Float32Array.BYTES_PER_ELEMENT, // How many floats can be made, but be even
dView = new DataView( new ArrayBuffer(Float32Array.BYTES_PER_ELEMENT) ), // ArrayBuffer/DataView to convert 4 bytes into 1 float.
fAry = new Float32Array(fLen), // Final Output at the correct size
p = 0; // Position
for(var j=0; j < fLen; j++){
p = j * 4;
dView.setUint8(0,blob.charCodeAt(p));
dView.setUint8(1,blob.charCodeAt(p+1));
dView.setUint8(2,blob.charCodeAt(p+2));
dView.setUint8(3,blob.charCodeAt(p+3));
fAry[j] = dView.getFloat32(0,true);
}
console.log(fAry); //Float32Array(9) [0, 0, 0, 1, 0, 0, 0, 1, 0] - Three Vectors to create a triangle for WebGL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment