toHex function

String toHex(
  1. dynamic number, {
  2. bool pad = false,
  3. bool include0x = false,
  4. int? forcePadLen,
})

Converts the number, which can either be a dart int or a BigInt, into a hexadecimal representation. The number needs to be positive or zero.

When pad is set to true, this method will prefix a zero so that the result will have an even length. Further, if forcePadLen is not null and the result has a length smaller than forcePadLen, the rest will be left-padded with zeroes. Note that forcePadLen refers to the string length, meaning that one byte has a length of 2. When include0x is set to true, the output wil have "0x" prepended to it after any padding is done.

Implementation

String toHex(dynamic number,
    {bool pad = false, bool include0x = false, int? forcePadLen}) {
  String toHexSimple() {
    if (number is int)
      return number.toRadixString(16);
    else if (number is BigInt)
      return number.toRadixString(16);
    else
      throw new TypeError();
  }

  var hexString = toHexSimple();
  if (pad && !hexString.length.isEven) hexString = "0$hexString";
  if (forcePadLen != null) hexString = hexString.padLeft(forcePadLen, "0");
  if (include0x) hexString = "0x$hexString";

  return hexString;
}