Ali Akbar
Ali Akbar

Reputation: 794

Convert 4 byte into a signed integer

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;
  }

Upvotes: 7

Views: 9384

Answers (3)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76353

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.buffer.asByteData().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);
}

Upvotes: 10

Cutch
Cutch

Reputation: 3575

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

Upvotes: 3

Kai Sellgren
Kai Sellgren

Reputation: 30312

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.

Upvotes: 2

Related Questions