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

Time:05-29

I have a list of int like the following.

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

I would like to generate 8/16/32 Uint so that I can process them. For example, bytes 2 & 3 is actually a 16 bit value, so both bytes need to be added, in the right order which in this case is 00000000 00101000 .

Question: How can I target specific index to add to a specific Uint type?

eg.. Uint16 powerValue = data[2] data[3];

CodePudding user response:

  1. Presuming that your List<int> is meant to be a list of bytes, convert your List<int> into a Uint8List with Uint8List.fromList. Note that your List<int> might already be a Uint8List; if so, just cast it with as Uint8List to avoid an unnecessary copy.

  2. Access the Uint8List.buffer getter to obtain the underlying ByteBuffer.

  3. You then can use methods such as ByteBuffer.asUint16List, ByteBuffer.asUint32List, etc. These methods allow you to specify a starting offset and length.

  4. Alternatively, if you need more control (for example, if you want to interpret bytes using the non-native endianness), then you can use ByteBuffer.asByteData to obtain a ByteData view that provides methods such as getUint16, getUint32, etc.

Putting it all together, for your specific example:

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
}

Of course, if this is just something you need to do as a one-off case, you also could just do bitwise operations yourself:

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