提问人:Ariel Marcelo Pardo 提问时间:10/30/2023 更新时间:10/30/2023 访问量:28
如何使用 Node js Buffer 同时处理 float IEEE 754 和 uint/int?
How can I deal with float IEEE 754 and uint/int at the same time using Node js Buffer?
问:
大家好:我必须用某种格式解析一些数据,这些格式涉及 uint、int with sign 和 float,试图优化字节的使用。我认为我可以体面地处理 uint/int 数字,因为我根据大小分配字节,但我不知道如何处理浮点数,因为我认为我无法优化我将使用的字节数量。例如,如果我必须转换为十六进制,则会出现以下两种情况:
format = [{ tag: "valor1", type: "uint", len: 2}, { tag: "valor2", type: "uint", len: 3}, {tag: "valor3", type: "uint", len:5}, { tag: "valor4", type: "int", len: 5}]
data = { valor1: 2, valor2: 7, valor3: 18, valor4: -15 }
或
format = [
{ tag: "PTemp", type: "int", len: 12 },
{ tag: "BattVolt.value", type: "int", len: 12 },
{ tag: "WaterLevel", type: "int", len: 8 },
];
data = { PTemp: 268, "BattVolt.value": 224, WaterLevel: 115 };
下一个代码返回我所期望的(5E 51 和 10C0E073):
class BinaryParser{
encode(_object, format){
let size = 0
let data = 0
format.forEach(e => {
size = size + e.len
})
const buffer = Buffer.alloc(Math.ceil(size/8))
format.forEach(elem => {
let value = _object[elem.tag]
switch (elem.type){
case 'int':
case 'uint':
if (value < 0) {
value = (1 <<elem.len) - Math.abs(value)
}
data = (data << elem.len) | value
buffer.writeUintBE(data,0,Math.ceil(size/8))
break;
}
})
return buffer
}}
我使用这样的代码:
const bp = new BinaryParser();
const dataEncoded = bp.encode(data, format);
console.log(dataEncoded.toString('hex'));
所以,这是 - 想想 - 好吧,但是,如果我想在数据中包含像 3.14 这样的浮点数会发生什么?比方说:
format = [
{ tag: "PTemp", type: "int", len: 12 },
{ tag: "BattVolt.value", type: "int", len: 12 },
{ tag: "WaterLevel", type: "int", len: 8 },
{ tag: "Phi", type: float}
];
data = { PTemp: 268, "BattVolt.value": 224, WaterLevel: 115, Phi: 3.14 };
如何以最优化的方式分配字节?
答: 暂无答案
评论