Skip to content

Instantly share code, notes, and snippets.

@nashfive
Created December 10, 2019 14:14
Show Gist options
  • Save nashfive/e4fcb88468731a085057839d0148ab7e to your computer and use it in GitHub Desktop.
Save nashfive/e4fcb88468731a085057839d0148ab7e to your computer and use it in GitHub Desktop.
Convert a hexadecimal string to a Uint16
import 'dart:typed_data';
/// Converts [input] to a Uint16.
///
/// For example, _decodeToUint16("734c") slices [input] into 2 substrings
/// of 2 hexa characters ('73' and '4c') and create a Uint8 list from their
/// respective decimal representation (i.e. [115, 76]).
///
/// Finally, it returns an unsigned 16-bits integer representation (little endian)
/// by using a [ByteData] view (i.e. '19571').
///
int hexStringToUint16(String input) {
// Slice the string in 2-char substrings and parse it from hex to decimal
final bytes = sliceString(input, 2).map((s) => int.parse(s, radix: 16));
// Create a Uint8 from the 2-bytes list
final u8list = Uint8List.fromList(bytes.toList());
// Return a Uint16 little endian representation
return ByteData.view(u8list.buffer).getUint16(0, Endian.little);
}
/// Slices the [input] string into a list of [count] substrings.
///
/// The [input] string must be divisible in substrings of equal length, otherwise
/// it will throw an [ArgumentError].
///
List<String> sliceString(String input, int count) {
if (input.isEmpty) return [];
if (input.length % count != 0) {
throw ArgumentError("Cannot slice $input in $count slices.");
}
final slices = List<String>(count);
int len = input.length;
int sliceSize = len ~/ count;
for (var i = 0; i < count; i++) {
var start = i * sliceSize;
slices[i] = input.substring(start, start + sliceSize);
}
return List.unmodifiable(slices);
}
@nashfive
Copy link
Author

Thanks! Glad that it helped you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment