javaParseInt function

int? javaParseInt(
  1. String s, {
  2. int bits = 32,
})

Java Integer.parseInt (32-bit) or, with bits 64, Long.parseLong.

Accepts an optional +/- sign followed by decimal digits (any Unicode decimal digit, as Java does); no whitespace, no 0x prefix. Returns null where Java throws NumberFormatException.

Implementation

int? javaParseInt(String s, {int bits = 32}) {
  if (s.isEmpty) return null;
  var i = 0;
  var negative = false;
  final first = s.codeUnitAt(0);
  if (first == 0x2D || first == 0x2B) {
    negative = first == 0x2D;
    i = 1;
    if (s.length == 1) return null;
  }
  var value = BigInt.zero;
  for (; i < s.length; i++) {
    final digit = javaDigit(s.codeUnitAt(i));
    if (digit < 0) return null;
    value = value * BigInt.from(10) + BigInt.from(digit);
  }
  if (negative) value = -value;
  final max = (BigInt.one << (bits - 1)) - BigInt.one;
  final min = -(BigInt.one << (bits - 1));
  if (value > max || value < min) return null;
  return value.toInt();
}