Reputation: 137
Context: I'm working on a lighting protocol converter for architectural LED matrices and need to encode byte strings in a very specific way for the headers to be recognized by my hardware.
Q: How can I convert an int into two bytes such that I can then use them separately?
Example:
I want to convert
var aDynamicValue = 511 //where value will range from 0-511
to a list like: [0x01, 0xFF]
Such that I can then
<BytesBuilder> magicString.add(--the bytes above--)
Thanks
Upvotes: 2
Views: 6552
Reputation: 75629
Use bit shifting together with logical AND
to mask out all but first 8 bits. Pseudo code:
a = 511;
byte1 = a & 0xff;
byte2 = (a >> 8) & 0xff;
Upvotes: 8
Reputation: 657138
typed_data and int.toRadixString(16)
can be used to get hex from integers:
final list = new Uint64List.fromList([511]);
final bytes = new Uint8List.view(list.buffer);
final result = bytes.map((b) => '0x${b.toRadixString(16).padLeft(2, '0')}');
print('bytes: ${result}');
Upvotes: 12