Node.js在字节数组中使用不同的数据types
例如:我将有数据包含字节(0-100),字节(0-10),两个字节(-30- + 100),布尔( 0/1),字节,两个字节(0-300)。
客户端将接收字节数组(使用缓冲区),并从缓冲区使用偏移量创build的hax中获取数据。 所以我需要始终保持在我从客户端获取的API规范中的字节数。
例:
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));
将返回:0x3202ec012022
这当然是不好的,因为两件事情:
-
-20是ec? 290是22? (第一个字节发生了什么?290 dec是0x122,这是两个字节)
-
事件如果是正确的(如果数字包含在一个字节中),我需要保持大小来保持偏移量,这不会保持偏移量,因为这里的所有数字都是一个字节的大小。
有谁知道如何解决这个问题?
你应该自己做治疗,我会使用一个定制的类。 喜欢 :
// 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()); }
编辑:更多的解释
您必须创build一个将处理数据存储和处理的类。
当我们正在处理一个数据时,我们将它的大小以Byte的forms存储起来。
例如3
字节中的数字12
,我们将存储{ value: 12, size: 3 }
。
当我们必须生成Byte数组时,我们将使用我们存储的大小来将正确数量的Byte推入Buffer
数组。
例如3
字节中的数字12
。
我们将存储在缓冲区0
和12
。
要清楚:
之前
array.push(12); new Buffer(array);
缓冲区读取数组,需要12
并将其转换为Byte,所以0x0C
你最终Buffer = [ 0x0C ]
现在
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());
你最终Buffer = [ 0x00, 0x00, 0x0C ]
两个字节(-30- + 100)//这个值没有问题。 -30是8位二进制补码有符号整数,因此可以存储在1个字节中。
两个字节(0-300)//可以存储在2个字节中。 将数字转换为exp的位。 使用(300).toString(2)并存储到2个字节。