Convert 4 byte into a signed integer

dart

Solution

You can use ByteArray from `typed_data` library.

import 'dart:typed_data';

int fromBytesToInt32(int b3, int b2, int b1, int b0) {
  final int8List = new Int8List(4)
    ..[3] = b3
    ..[2] = b2
    ..[1] = b1
    ..[0] = b0;
  return int8List.asByteArray().getInt32(0);
}

void main() {
  assert(fromBytesToInt32(0x00, 0x00, 0x00, 0x00) == 0);
  assert(fromBytesToInt32(0x00, 0x00, 0x00, 0x01) == 1);
  assert(fromBytesToInt32(0xF0, 0x00, 0x00, 0x00) == -268435456);
}

Problem

I'm trying to parse a binary file in the browser. I have 4 bytes that represent a 32-bit signed integer. Is there a straight forward way of converting this to a dart int, or do I have to calculate the inverse of two's complement manually? Thanks Edit: Using this for manually converting: ``` int readSignedInt() { int value = readUnsignedInt(); if ((value & 0x80000000) > 0) { // This is a negative number. Invert the bits and add 1 value = (~value & 0xFFFFFFFF) + 1; // Add a negative sign value = -value; } return value; } ```

Original source