base32hexEncode function

String base32hexEncode(
  1. List<int> input, {
  2. bool addPadding = true,
})

Encodes input bytes to a Base32Hex string.

When addPadding is true (default) the output is padded to a multiple of 8 characters with =. Pass false to suppress padding - this is what the bysquare wire format expects.

Implementation

String base32hexEncode(List<int> input, {bool addPadding = true}) {
  final output = StringBuffer();
  int buffer = 0;
  int bitsLeft = 0;

  for (final byte in input) {
    buffer = (buffer << 8) | (byte & 0xFF);
    bitsLeft += 8;

    while (bitsLeft >= _bits) {
      bitsLeft -= _bits;
      output.writeCharCode(_chars.codeUnitAt((buffer >> bitsLeft) & _mask));
    }
  }

  if (bitsLeft > 0) {
    final maskedValue = (buffer << (_bits - bitsLeft)) & _mask;
    output.writeCharCode(_chars.codeUnitAt(maskedValue));
  }

  var result = output.toString();

  if (addPadding) {
    final paddedLength = ((result.length + 7) ~/ 8) * 8;
    result = result.padRight(paddedLength, '=');
  }

  return result;
}