I'm looking for an efficient way to store an array of THREE.Vector3 objects in local storage using JavaScript. Since JavaScript operates with strings, I need to convert a 32-bit float to a string using the best bit ratio possible, ideally equating 32-bit float to 4 * 8 bits, similar to how it's done in C++.
However, there are two main issues I'm facing. Firstly, JavaScript strings are encoded in UTF-8 which includes some padding.
http://en.wikipedia.org/wiki/UTF-8
Secondly, the code I'm currently using converts 0 to '' which then gets omitted, leading to unreliable byte length conversion.
var float2str = function(num) {
var bytestream = new Array();
var view = new DataView(new ArrayBuffer(4));
view.setFloat32(0, num);
bytestream.push(view.getUint8(0));
bytestream.push(view.getUint8(1));
bytestream.push(view.getUint8(2));
bytestream.push(view.getUint8(3));
return String.fromCharCode(view.getUint8(0), view.getUint8(1), view.getUint8(2), view.getUint8(3));
}
var str2float = function(str) {
var bytestream = unpack(str);
var view = new DataView(new ArrayBuffer(4));
view.setUint8(0, bytestream[0]);
view.setUint8(1, bytestream[1]);
view.setUint8(2, bytestream[2]);
view.setUint8(3, bytestream[3]);
return view.getFloat32(0);
}
Thank you!