fromBytes static method
Converts a list of bytes to an integer, following the given byte order.
offset specifies the starting index within bytes to read from.
length specifies how many bytes to read (defaults to the rest of the list).
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, {
int offset = 0,
int? length,
Endian byteOrder = Endian.big,
bool sign = false,
}) {
final int len = length ?? (bytes.length - offset);
if (offset < 0 || len < 0 || offset + len > bytes.length) {
throw CoreErrors.invalidOperationArguments(
'fromBytes',
name: 'offset',
reason:
'Invalid offset/length: offset=$offset, length=$len, bytes.length=${bytes.length}.',
);
}
if (len == 0) return 0;
// Large inputs: hand off directly to BigInt decoding using
// offset/length, without copying the (potentially huge) slice here.
if (len > 6) {
final big = BigintUtils.fromBytes(
bytes,
offset: offset,
length: len,
byteOrder: byteOrder,
sign: sign,
);
if (big.isSafeInt()) return big.toInt();
throw CoreErrors.invalidOperationArguments(
'fromBytes',
name: 'bytes',
reason: 'Value too large to fit in a Dart int.',
);
}
// Small inputs (<= 6 bytes): build a tiny local list directly,
// no need to touch/copy anything beyond the relevant window.
final ordered = List<int>.generate(
len,
(i) =>
byteOrder == Endian.little
? bytes[offset + len - 1 - i]
: bytes[offset + i],
);
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) {
final int n = ordered.length * 8;
final int subtrahend =
n < 32 ? (1 << n) : ((1 << (n - 32)) * 0x100000000);
result -= subtrahend;
}
return result;
}