简体   繁体   中英

Convert int to two bytes in hex?

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

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;

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}');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM