1、解析二进制流工具类
public static void main(String[] args){
//假设这是你要解析的二进制字节流
byte[] bytes = new byte[];
//声明一个 int[] 用于记录下标;
int[] off = new int[] {0};
//调用解析方法
String data = getData(bytes,off,"int");
System.out.println("解析结果" + data);
}
//bytes 代表要解析的byte数组,
//start 代表截取的下标从什么开始,
//fieldType 代表你要解析的类型,比如现在已有三种 int、double、char,想要解析别的类型可以再去网上找,查找的方法是,java解析shaor类型的c++二进制字节流
public static String getData(byte[] bytes, int[] start, String fieldType){
if(start[0] > bytes.length){
System.out.println("超出");
return "";
}
String result = "";
byte[] bytes1 = new byte[0];
if ("int".equalsIgnorecase(fieldType)|| "Integer".equalsIgnorecase(fieldType)) {
bytes1 = splitByteArr(bytes,start,4);
return String.valueof(byteArrayToInt(bytes1));
} else if("double".equalsIgnorecase(fieldType)){
bytes1=splitByteArr(bytes,start,8);
return String.value0f(bytesToDouble(bytes1));
}else if("char".equalsIgnorecase(fieldType)){
bytes1 = splitByteArr(bytes,start,30);
return byteToStr(bytes1);
}
return;
}
//bytes 代表要解析的byte数组,start 代表截取的下标从什么开始,len 代表要解析的这个类型有多少字节
public static byte[] splitByteArr(byte[] bytes, int[] start, int len){
byte[] result = new byte[len];
if(start[0] + len > bytes.length) {
return result;
}
fon(int i = 0; i < len; i++) {
result[il = bytes[start[0] + i];
}
start[0] += len;
return result;
}
public static int byteArrayToInt(byte[] bytes){
int value = 0;
for(int i = 0; i< 4; i++) {
value |= ((int)(bytes[i] & 0xff)) << (8 * 1);
return value;
}
public static double bytesToDouble(byte[] bytes){
long value = 0;
for(int i = 0; i < 8; i++){
value |= ((long) (data[i] & 0xff)) << (8 * 1);
}
double a =(double) Math.round(Double.longBitsToDouble(value) * 1000) / 1000;
return Double.value0f(BigDecimal.value0f(a).setScale(5,BigDecimal.ROUND_HALF_up).toEngineeringString());
}
public static String byteToStr(byte[] bytes){
Charset cs =Charset.forName("utf-8");
ByteBuffer bb = ByteBuffer.allocate(bytes.length);
bb.put(bytes);
bb.flip();
CharBuffer cb=cs.decode(bb);
char[] array = cb.array();
return new String(array);
}