Dart convert two Uint8's to one Uint16
You can simply use binary shift which should be super efficient:
(list[0] << 8) + list[1]
Demo:
var list = new Uint8List(2);
list[0] = 1;
list[1] = 1;
print((list[0] << 8) + list[1]);
Vincent Guttmann
I'm a young guy who lives in Germany and programs in his free time. Mostly Arduino ;) but also Python, Bash, PowerShell for automation purposes, and, I'm learning Dart/flutter right now.
Updated on December 22, 2022Comments
-
Vincent Guttmann over 1 year
I am building an app to read data from a spectrophotometer via Bluetooth. The measurements are sent as two bytes meant to be converted to one unsigned 16-bit integer. Thanks to the library I am using for the Bluetooth communication, those two bytes are converted two a Uint8List.
I have looked around, but I have found no solution whatsoever. How would I do that here?
I don't care if it's pretty. Heck, if you would provide a solution that uses black magic, I would use it. The only thing it has to do is to do its job, even if it's slow. I only need to get out three Uint16's, and the acceptable timespan is about one second, so even the most inefficient solution will do here.
-
Vincent Guttmann over 3 yearsI took a different approach: I just converted both numbers to a RadixString, added both together (well, I appended one to the other, to be precise), and then uses int.parse to get it back into an int. I'm sure it's not the best solution, but since I only need to merge six numbers into three, this should be no problem for a modern smartphone processor (Heck, I bet my trusty bricky TI-84+ could run that pretty smoothly).
-
fsw over 3 yearsBinary shift should translate to single procesor operation. Converting to string, concatenating and converting back will in fact translate to lots of logic and memory operations. Also this operator is exactly for such cases so your solution would also require more complex and less readable source code in my opinion. But if you don't mind this then sure, it will work. cheers.
-
Vincent Guttmann over 3 yearsSo I was troubleshooting the algorithm recently (as it turns out, high and low byte were flipped in comparison to the documentation), and I just rewrote the algorithm with binary shift. At the time, I didn't understand what it did (because I didn't read about it, as I already had a solution that worked), but after reading it, I just used that instead of parsing as binary, concatenating and so forth. I hope that you are happy now ;)