Convert 4 byte into a signed integer

两盒软妹~` 提交于 2021-02-18 11:43:21

问题


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

回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/13322327/convert-4-byte-into-a-signed-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!