四个字节转无符号整型java,从2或4个字节转换为有符号/无符号short / int
时间: 2024-01-15 07:05:40 浏览: 295
四个字节转无符号整型Java可以使用如下代码:
```java
public static long bytesToUnsignedInt(byte[] bytes) {
long value = 0;
for (int i = 0; i < bytes.length; i++) {
value += ((long) bytes[i] & 0xffL) << (8 * i);
}
return value;
}
```
对于2或4个字节转换为有符号/无符号short/int,可以使用Java中的ByteBuffer类进行转换。以下是示例代码:
```java
// 2字节有符号short转换为无符号short
short signedShort = -1;
int unsignedShort = Short.toUnsignedInt(signedShort);
// 4字节有符号int转换为无符号int
int signedInt = -1;
long unsignedInt = Integer.toUnsignedLong(signedInt);
// 2字节无符号short转换为有符号short
int unsignedShort = 65535;
short signedShort = (short) unsignedShort;
// 4字节无符号int转换为有符号int
long unsignedInt = 4294967295L;
int signedInt = (int) unsignedInt;
```
阅读全文