Converting Array Of Binary Doubles In Protocol Buffer To Javascript Numbers
I'm using protocol buffers over zeroMQ to send graph data from C++ to a Javascript frontend: message RawData { Type type = 1; bytes data = 2; } when i call RawData.getData()
Solution 1:
Just divide the result in 8 elements parts and use ArrayBuffer and Dataview to mount the number. Example:
function splitData(data) {
return data.reduce(function(a, b, c){
if(c % 8 == 0 && c !== 0){
a.push([]); };
a[a.length - 1].push(b);
return a;
}, [[]]);
}
function computeValues(data, littleEndian = false) {
var res = [];
splitData(data).forEach(numberElement=>{
var buffer = new ArrayBuffer(8);
var dv = new DataView(buffer);
numberElement.forEach((val, ix)=>dv.setUint8(littleEndian ? 7 - ix : ix, val));
res.push(dv.getFloat64(0));
});
return res;
}
var data = [0, 0, 0, 0, 0, 0, 0, 0, 64, 1, 118, 62, 112, 8, 12, 63];
console.log(computeValues(data));
console.log(computeValues(data, true));
The data.reduce
function is taken from this SO answer: Splitting a JS array into N arrays
JSFiddle: https://jsfiddle.net/z3fL39sr/12/
littleEndian parameter refers to the order of the bytes. If the most significant came first, set littleEndian to true. This page explains about endianess if you need it: https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html
Post a Comment for "Converting Array Of Binary Doubles In Protocol Buffer To Javascript Numbers"