将4字节转换为有符号整数 [英] Convert 4 byte into a signed integer
本文介绍了将4字节转换为有符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在浏览器中解析一个二进制文件.我有4个字节,代表一个32位带符号整数.
是否有将其转换为dart int的简便方法,还是我必须手动计算二进制补码的逆数?
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?
谢谢
使用它进行手动转换:
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;
}
推荐答案
您可以使用 typed_data 库中的rel ="nofollow noreferrer"> ByteArray .
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);
}
这篇关于将4字节转换为有符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文