fromBytes static method
Converts a list of bytes to an integer, following the given byte order.
Uses native int math when safe; otherwise decodes via BigInt and
checks isValidInt before converting back, throwing instead of
silently losing precision.
Implementation
static int fromBytes(
List<int> bytes, {
Endian byteOrder = Endian.big,
bool sign = false,
}) {
if (bytes.isEmpty) return 0;
if (bytes.length > 6) {
final big = BigintUtils.fromBytes(
bytes,
byteOrder: byteOrder,
sign: sign,
);
if (big.isValidInt) return big.toInt();
throw ArgumentException.invalidOperationArguments(
'fromBytes',
name: 'bytes',
reason: 'Value too large to fit in a Dart int.',
);
}
final ordered =
byteOrder == Endian.little ? bytes.reversed.toList() : bytes;
int result;
if (ordered.length > 4) {
final int upperPart = _fromBytesUpTo4(
ordered.sublist(0, ordered.length - 4),
);
final int lowerPart = _fromBytesUpTo4(
ordered.sublist(ordered.length - 4),
);
result = upperPart * 0x100000000 + lowerPart; // avoid << 32
} else {
result = _fromBytesUpTo4(ordered);
}
if (sign && (ordered[0] & 0x80) != 0) {
result -= 1 << (ordered.length * 8); // safe: length*8 <= 48 bits here
}
return result;
}