hexToU8a function

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

value sholud be 0x hex

Implementation

Uint8List hexToU8a(String value, [int bitLength = -1]) {
  try {
    if (!isHex(value) && !isHexString(value)) {
      throw 'Error: Expected hex value to convert, found $value';
    }
    var _value = hexStripPrefix(value);
    var valLength = _value.length / 2;
    var bufLength = (bitLength == -1 ? valLength : bitLength / 8).ceil();

    var result = Uint8List(bufLength);
    var offset = max(0, bufLength - valLength).toInt();

    for (var index = 0; index < bufLength - offset; index++) {
      var subStart = index * 2;
      var subEnd = subStart + 2 <= _value.length ? subStart + 2 : _value.length;
      var arrIndex = index + offset;
      result[arrIndex] =
          int.tryParse(_value.substring(subStart, subEnd), radix: 16)!;
    }
    return result;
  } catch (e) {
    throw "Error: hexToU8a $e";
  }
}