javascript - Node.js using deferent data types in bytes array -


i need create byte array deferent data types in it, example: have data contain byte (0-100), byte(0-10), 2 bytes(-30-+100), bool(0/1), byte, 2 bytes(0-300).

the client receive bytes array (using buffer) , data hax buffer creates using offsets. need retain number of bytes in api specs i'm getting 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 not because of 2 things:

  1. -20 ec? , 290 22? (what happen first byte? 290 dec 0x122 , 2 bytes)

  2. event if correct (if numbers contained in single byte), need keep sizes maintain offsets , not maintain offsets numbers on here of size of 1 byte.

does 1 knows how solve issue?

you should treatment yourself, use of customized class. :

// use of array, gonna hold data using describing structure this.array = [];  // store values along size in byte push(value, size) {   this.array.push({     size,     value,   }); }  // turn array byte array getbytearray() {   // create byte array   return this.array.reduce((tmp, {     size,     value,   }) => {     // here makes multiple insertion in buffer depending on size have      // example if have value 0 size of 4.     // make 4 push on buffer     tmp.push(...);      return tmp;   }, new buffer()); } 

edit: more explanation

you have create class handle data storage , treatment.

when dealing data, store associated it's size in byte.

for example number 12 in 3 byte, gonna store { value: 12, size: 3 }.

when gonna have generate byte array, gonna use size did store in order push correct amount of byte buffer array.

for example number 12 in 3 byte.

we gonna store in buffer 0, 0 , 12.


to clear :

before

array.push(12);  new buffer(array); 

the buffer read array, takes 12 , convert byte, 0x0c

you end buffer = [ 0x0c ]


now

array.push({ value: 12, size: 3 });  array.reduce( ...   // because have size of 3 byte, push 3 byte in buffer   buffer.push(0);  buffer.push(0);  buffer.push(12);  ..., new buffer()); 

you end buffer = [ 0x00, 0x00, 0x0c ]


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -