hexToU8a function

Uint8List hexToU8a(
  1. String value, [
  2. int bitLength = -1
])

value should be 0x hex string.

Implementation

Uint8List hexToU8a(String value, [int bitLength = -1]) {
  if (!isHex(value)) {
    throw ArgumentError.value(value, 'value', 'Not a valid hex string');
  }
  final newValue = hexStripPrefix(value);
  final valLength = newValue.length / 2;
  final bufLength = (bitLength == -1 ? valLength : bitLength / 8).ceil();
  final result = Uint8List(bufLength);
  final offset = math.max(0, bufLength - valLength).toInt();
  for (int index = 0; index < bufLength - offset; index++) {
    final subStart = index * 2;
    final subEnd =
        subStart + 2 <= newValue.length ? subStart + 2 : newValue.length;
    final arrIndex = index + offset;
    result[arrIndex] = int.parse(
      newValue.substring(subStart, subEnd),
      radix: 16,
    );
  }
  return result;
}