四字节读取16进制文件,并将四位16进制存储的字节数组以低位到高位转换成整数
原始数据截图如下:比如00 80 C2 AD转为AD C2 80 00再转为十进制
public static long readFile4Byte(String fileName) throws Exception {
FileInputStream fis =new FileInputStream("D://2");
byte[] buf=new byte[4];
int tempByte=-1;
long value=0;
StringBuffer sb = new StringBuffer();
while((tempByte=fis.read(buf))!=-1){
String s=bytesToHex(buf);//将字节数组转换为16进制字符串
long i = Long.parseLong(s,16);//将16进制字符串转为10进制
System.out.println("i :"+i );
}
fis.close();
return value;
}
/**
* 字节数组转16进制
*/
public static String bytesToHex(byte[] bytes) {
bytes=byteReverse(bytes);//将字节数组逆序
StringBuffer sb = new StringBuffer();
for(int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if(hex.length() < 2){
sb.append(0);
}
sb.append(hex);
}
return sb.toString();
}
/**
* 字节数组逆序
*/
public static byte[] byteReverse(byte[] a) {
byte temp=a[0];
a[0]=a[3];
a[3]=temp;
temp=a[1];
a[1]=a[2];
a[2]=temp;
return a;
}
输出结果
希望对你有帮助