将协议缓冲区中的二进制双精度数组转换为 javascript 数字
我正在使用 zeroMQ 上的协议缓冲区将图形数据从 C++ 发送到 Javascript 前端:
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;
}
当我调用 RawData.getData() 时,我得到这样的信息(通常更长):
when i call RawData.getData() i get something like this (usually much longer):
数据:0, 0, 0, 0, 0, 0, 0, 0, 64, 1, 118, 62, 112, 8, 12, 63
这是两个 8 字节的数字,其中数组中的每个索引为 1 个字节.
This is two 8 bytes numbers, where each index in the array is 1 byte.
如何在 Javascript 中将其转换为双重表示?
How do I convert this into double representation in Javascript?
我最终将协议缓冲区消息更改为 repeated double data = 2;
i ended up changing the protocol buffer message to repeated double data = 2;
这消除了转换的需要
只需将结果分成 8 个元素部分,并使用 ArrayBuffer 和 Dataview 挂载数字.示例:
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));
data.reduce
函数取自这个 SO 答案:将一个 JS 数组拆分成 N 个数组
The data.reduce
function is taken from this SO answer: Splitting a JS array into N arrays
JSFiddle:https://jsfiddle.net/z3fL39sr/12/
littleEndian 参数指的是字节的顺序.如果最重要的在前,则将 littleEndian 设置为 true.如果需要,此页面解释了字节序:https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html
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