用Java解析二进制文件,一般会碰到文件中含有无符号格式的数字,而Java的基本数据类型只支持有符号类型。
转换方法:
1.按byte读取
2.将byte数组转换成相应的Java基本类型。一般情况下,UNIT16转换成int,UNIT8转换成short,UNIT32转换成long。
下面仅举例UNIT16转换成int,其中,为了防止输入的byte数组长度,不是2,做了保护。(超过4的字节的处理),如果会造成性能问题,同时保证不会传入超过4个字节的参数,可以不保护。
public class Main {
// 将2个字节转换成int
private static int toInt(byte[] bytes) {
int ret = ((bytes[0] & 0xff) << 8) | (bytes[1] & 0xff);
return ret;
}
// 将2个网络字节序字节转换成int
private static int toRInt(byte[] bytes) {
int ret = ((bytes[1] & 0xff) << 8) | (bytes[0] & 0xff);
return ret;
}
// 将size个字节转换成int,其中如果size〉4,取后四位
private static int toInt(byte[] bytes, int size) {
int ret = 0;
int beginPos = size > 4 ? size - 4 : 0;
for (int i = beginPos; i < size; ++i) {
ret = (ret << 8) | (bytes[i] & 0xff);
}
return ret;
}
// 将size个网络字节序字节转换成int,其中如果size〉4,取前四位
private static int toRInt(byte[] bytes, int size) {
int ret = 0;
int beginPos = size > 4 ? 4 : size;
for (int i = beginPos - 1; i >= 0; --i) {
ret = (ret << 8) | (bytes[i] & 0xff);
}
return ret;
}
public static void main(String[] args) {
byte[] b2 = new byte[] { -1, -1 };
int n1 = toInt(b2, 2);
int n2 = toRInt(b2, 2);
int n11 = toInt(b2);
int n22 = toRInt(b2);
byte[] b3 = new byte[] { 10, 0 };
int n3 = toInt(b3, 2);
int n4 = toRInt(b3, 2);
short s = (short) n3;
int n5 = Short.reverseBytes(s);
int n33 = toInt(b3);
int n44 = toRInt(b3);
int n6 = toInt((short) -1);
int n7 = toRInt((short) -1);
int n8 = toInt((short) n3);
int n9 = toRInt((short) n4);
}
private static int toInt(short shortVal) {
int ret = shortVal > 0 ? shortVal : (shortVal & 0xffff);
return ret;
}
private static int toRInt(short shortVal) {
shortVal = Short.reverseBytes(shortVal);
int ret = shortVal > 0 ? shortVal : (shortVal & 0xffff);
return ret;
}
}