Hello everyone: I have to parse some data with some format that involves uint, int with sign and float trying to optimize the using of bytes. I think I can handle decently with uint/int numbers because I alloc bytes accordingly to the size but i don't know how to work with floating numbers because I think that I can't optimize the amount of bytes that I would use. For example, if I have to convert to hexadecimal this two situations:
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 }
or
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 };
the next code return what I expected (5E 51 and 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
}}
I used the code like this:
const bp = new BinaryParser();
const dataEncoded = bp.encode(data, format);
console.log(dataEncoded.toString('hex'));
So, that's- think- ok but, what happend if I want to include in data a float number like 3.14? Let say:
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 };
How can I alloc bytes the most optimize way?