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:
Presuming that your
List<int>
is meant to be a list of bytes, convert yourList<int>
into aUint8List
withUint8List.fromList
. Note that yourList<int>
might already be aUint8List
; if so, just cast it withas Uint8List
to avoid an unnecessary copy.Access the
Uint8List.buffer
getter to obtain the underlyingByteBuffer
.You then can use methods such as
ByteBuffer.asUint16List
,ByteBuffer.asUint32List
, etc. These methods allow you to specify a starting offset and length.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 aByteData
view that provides methods such asgetUint16
,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];