intFromBytes function

int intFromBytes(
  1. List<int> bytes,
  2. Endian endian
)

Convert a list of bytes to an integer with the specified endianness. This function takes a list of bytes 'bytes' and an 'endian' parameter indicating the byte order (Endian.little or Endian.big), and converts the bytes into an integer. It supports byte lengths of 1, 2, and 4 bytes, and throws an error for unsupported lengths. If 'bytes' is empty, it raises an ArgumentError.

Implementation

int intFromBytes(List<int> bytes, Endian endian) {
  if (bytes.isEmpty) {
    throw ArgumentError("Input bytes should not be empty");
  }

  /// Create a Uint8List from the input bytes.
  final buffer = Uint8List.fromList(bytes);

  /// Create a ByteData view from the Uint8List.
  final byteData = ByteData.sublistView(buffer);

  /// Use a switch statement to handle different byte lengths.
  switch (bytes.length) {
    case 1:
      return byteData.getInt8(0);
    case 2:
      return byteData.getInt16(0, endian);
    case 4:
      return byteData.getInt32(0, endian);
    default:
      throw ArgumentError("Unsupported byte length: ${bytes.length}");
  }
}