Node.js 在字节数组中使用不同的数据类型

Node.js using deferent data types in bytes array

我需要创建一个包含不同数据类型的字节数组,例如:我的数据将包含字节 (0-100)、字节 (0-10)、两个字节 (-30-+ 100), 布尔(0/1), 字节, 两个字节(0-300).

客户端将接收字节数组(使用 Buffer)并从 Buffer 使用偏移量创建的 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));

将 return: 0x3202ec012022

这当然不好,因为有两点:

  1. -20是ec吗? 290 是 22? (第一个字节发生了什么?290 dec 是 0x122,这是两个字节)

  2. 事件如果正确(如果数字包含在单个字节中),我需要保持大小以保持偏移量并且这不会保持偏移量因为这里的所有数字都是一个字节的大小。

有人知道如何解决这个问题吗?

你应该自己做治疗,我会使用定制的class。喜欢:

// 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());
}

编辑:更多解释

您必须创建一个 class 来处理数据存储和处理。

当我们处理一个数据时,我们将它与它的大小相关联地存储在字节中。

例如 3 字节中的数字 12,我们将存储 { value: 12, size: 3 }.

当我们必须生成字节数组时,我们将使用我们存储的大小,以便将正确数量的字节推送到 Buffer 数组中。

例如 3 字节中的数字 12

我们将存储在缓冲区 0012


要清楚:

之前

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 位二进制补码符号整数中的 es,因此可以存储在 1 个字节中。

Two Bytes(0-300) // 可以存储在 2 个字节中。将数字转换为 exp 的位。使用 (300).toString(2) 并存储到 2 个字节中。