decodeHex function

Uint8List decodeHex(
  1. String text
)

Decodes hexadecimal text into bytes. Accepts either case.

Throws FormatException on an odd length or a character outside 0-9, a-f, A-F — there is no lenient mode, because a stored hash that does not parse is a problem to surface, not to paper over.

Implementation

Uint8List decodeHex(String text) {
  if (text.length.isOdd) {
    throw FormatException('Hex string has an odd length', text);
  }
  final out = Uint8List(text.length ~/ 2);
  for (var i = 0; i < out.length; i++) {
    final high = _hexDigit(text, i * 2);
    final low = _hexDigit(text, i * 2 + 1);
    out[i] = (high << 4) | low;
  }
  return out;
}