base32hexDecode function

Uint8List base32hexDecode(
  1. String input, {
  2. bool loose = false,
})

Decodes a Base32Hex input string back to bytes.

When loose is true the input is uppercased and missing padding is added automatically. This is useful when reading QR codes that may omit padding.

Implementation

Uint8List base32hexDecode(String input, {bool loose = false}) {
  if (loose) {
    input = input.toUpperCase();
    final paddingNeeded = (8 - (input.length % 8)) % 8;
    input += '=' * paddingNeeded;
  }

  input = input.replaceAll(RegExp(r'=+$'), '');

  final output = <int>[];
  int buffer = 0;
  int bitsLeft = 0;

  for (int i = 0; i < input.length; i++) {
    final index = _chars.indexOf(input[i]);
    if (index == -1) {
      throw ArgumentError('Invalid Base32Hex character: "${input[i]}"');
    }

    buffer = (buffer << _bits) | index;
    bitsLeft += _bits;

    if (bitsLeft >= 8) {
      bitsLeft -= 8;
      output.add((buffer >> bitsLeft) & 0xFF);
    }
  }

  return Uint8List.fromList(output);
}