如何将 int 数组中的特定 int(位)定位为 Uint16 或 32?

How to target specific int (bits) in an int array into Uint16 or 32?

我有一个如下所示的 int 列表。

List<int> data = [52, 24, 40, 0, 198, 7, 98, 0, 0, 0, 40, 223, 30, 0, 203, 244, 0, 0]

我想生成 8/16/32 Uint 以便我可以处理它们。例如,字节 2 和 3 实际上是一个 16 位值,因此需要以正确的顺序添加两个字节,在本例中为 00000000 00101000 .

问题:如何定位特定索引以添加到特定 Uint 类型?

eg.. Uint16 powerValue = data[2] data[3];
  1. 假设您的 List<int> 是一个字节列表,将您的 List<int> 转换为带有 Uint8List.fromList. Note that your Uint8List;如果是这样,只需将其与 as Uint8List 一起使用以避免不必要的复制。

  2. 访问Uint8List.buffer getter获取底层ByteBuffer.

  3. 然后您可以使用ByteBuffer.asUint16List, ByteBuffer.asUint32List等方法。这些方法允许您指定起始偏移量和长度。

  4. 或者,如果您需要更多控制(例如,如果您想使用 non-native 字节序来解释字节),那么您可以使用 ByteBuffer.asByteData to obtain a ByteData view that provides methods such as getUint16, getUint32,等等

将它们放在一起,对于您的具体示例:

import 'dart:typed_data';

void main() {
  List<int> data = [
    52,
    24,
    40,
    0,
    198,
    7,
    98,
    0,
    0,
    0,
    40,
    223,
    30,
    0,
    203,
    244,
    0,
    0
  ];
  var bytes = Uint8List.fromList(data);
  var powerValue = bytes.buffer.asByteData().getUint16(2, Endian.little);
  print(value); // Prints: 40
}

当然,如果这只是你需要做的one-off情况,你也可以自己做位运算:

var powerValue = (data[3] << 8) | data[2];