6

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;
  }
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Ali Akbar
  • 764
  • 1
  • 9
  • 13

3 Answers3

8

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);
}
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • 2
    This has been changed to `dart:typed_array`. Heres [ByteData](https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:typed_data.ByteData), which is the rough equivalent of the previous `ByteArray` – beatgammit Mar 10 '15 at 05:40
  • Changed to `int8List.buffer.asByteData().getInt32(0);` – NecroMancer Oct 18 '22 at 19:29
3

Place the 4 bytes in a ByteArray and extract the Int32 like this:

import 'dart:scalarlist';

void main() {
  Int8List list = new Int8List(4);
  list[0] = b0;
  list[1] = b1;
  list[2] = b2;
  list[3] = b3;
  int number = list.asByteArray().getInt32(0);
}

John

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Cutch
  • 3,511
  • 1
  • 18
  • 12
2

I'm not exactly sure what you want, but maybe this code sample might get you ideas:

int bytesToInteger(List<int> bytes) {
  var value = 0;

  for (var i = 0, length = bytes.length; i < length; i++) {
    value += bytes[i] * pow(256, i);
  }

  return value;
}

So let's say we have [50, 100, 150, 250] as our "4 bytes", the ending result is a 32-bit unsigned integer. I have a feeling this isn't exactly what you are looking for, but it might help you.

Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87