问题
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() i get something like this (usually much longer):
Data: 0, 0, 0, 0, 0, 0, 0, 0, 64, 1, 118, 62, 112, 8, 12, 63
This is two 8 bytes numbers, where each index in the array is 1 byte.
How do I convert this into double representation in Javascript?
EDIT:
i ended up changing the protocol buffer message to repeated double data = 2;
this removed the need for conversion
回答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
来源:https://stackoverflow.com/questions/42985471/converting-array-of-binary-doubles-in-protocol-buffer-to-javascript-numbers