I need to create a byte array with deferent data types in it, For example: i will have data that will contain Byte (0-100), Byte(0-10), Two bytes(-30-+100), Bool(0/1), Byte, Two Bytes(0-300).
The client will receive the bytes array (using Buffer) and will get the data from the hax that Buffer creates by using offsets. So i need to always retain the number of bytes as in the API specs i'm getting from the client.
Example:
Battery.protorype.onSubscribe = function(maxValuesSize, updateValueCallback) {
var bytes = Array(6);
bytes[0] = 50;
bytes[1] = 2;
bytes[2] = -20;
bytes[3] = true;
bytes[4] = 32;
bytes[5] = 290;
updateValueCallback(new Buffer(bytes));
Will return: 0x3202ec012022
This of course is not good because of two things:
-20 is ec? and 290 is 22? (what happen to the first byte? 290 dec is 0x122 and this is two bytes)
Event if that was correct (if the numbers were contained in a single byte), I need to keep the sizes to maintain offsets and this does not maintain offsets as all the numbers over here are of size of one byte.
Does any one knows how to solve this issue?
You should do the treatment yourself, I would use of a customized class. Like :
// Use of an array, where you gonna hold the data using describing structure
this.array = [];
// Store values along with the size in Byte
push(value, size) {
this.array.push({
size,
value,
});
}
// Turn the array into a byte array
getByteArray() {
// Create a byte array
return this.array.reduce((tmp, {
size,
value,
}) => {
// Here you makes multiple insertion in Buffer depending on the size you have
// For example if you have the value 0 with a size of 4.
// You make 4 push on the buffer
tmp.push(...);
return tmp;
}, new Buffer());
}
EDIT: more explanation
You have to create a class that will handle the data storage and treatment.
When we are dealing with a data, we store it associated with it's size in Byte.
for example the number 12
in 3
Byte, we gonna store { value: 12, size: 3 }
.
When we gonna have to generate the Byte array, we gonna use the size we did store in order to push the correct amount of Byte into the Buffer
array.
for example the number 12
in 3
Byte.
We gonna store in the Buffer 0
, 0
and 12
.
To be clear :
BEFORE
array.push(12);
new Buffer(array);
The buffer read the array, takes 12
and convert it into Byte, so 0x0C
You end up with Buffer = [ 0x0C ]
NOW
array.push({ value: 12, size: 3 });
array.reduce( ...
// Because we have a size of 3 byte, we push 3 Byte in the buffer
buffer.push(0);
buffer.push(0);
buffer.push(12);
..., new Buffer());
You end up with Buffer = [ 0x00, 0x00, 0x0C ]