参考文章 Java 十六进制(Hex)与byte数组之间的转换
总体思路:
16进制 ---> 转为byte字节
---> 取具体约定的字节个数组成字节数组
---> 调用 new String(nameBytes,"GB18030") 方法获得中文或者英文
import net.sf.json.JSONArray;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;
public class ParseHex {
public static <T> List<T> parsePrintDataToList(String printData,String filePath) throws IOException {
byte[] printBytes = hexToByteArray(printData);
System.out.println(Arrays.toString(printBytes));
byte index = printBytes[0];
byte[] nameBytes = new byte[index];
Map<String,Object> map = new HashMap<>(16);
if (index >= 0) { System.arraycopy(printBytes, 1, nameBytes, 0, index); }
String name = new String(nameBytes,"GB18030");
System.out.println(name);
List<String> fields = Files.lines(FileSystems.getDefault().getPath(filePath))
.map(str -> str.substring(0,1).toLowerCase() + str.substring(1))
.collect(Collectors.toList());
System.out.println("List<String> fields = " +fields);
int current = 1+index;
List<Map<String,Object>> list = new ArrayList<>() ;
int fieldIndex =0;
while (current<printBytes.length) {
current = current + 3;
int length = (int)printBytes[current];
current = current+1;
byte[] contentBytes = new byte[length];
if (length >= 0) {
System.arraycopy(printBytes, current, contentBytes, 0, length);
}
String content = new String(contentBytes,"GB18030");
map.put(fields.get(fieldIndex),content);
fieldIndex = fieldIndex +1;
current = current + length;
}
list.add(map);
return (List<T>) list;
}
private static byte[] hexToByteArray(String inHex) {
int hexLen = inHex.length();
byte[] result;
if (hexLen % 2 == 1){
hexLen++;
result = new byte[(hexLen / 2)];
inHex = "0" + inHex;
}else {
result = new byte[(hexLen / 2)];
}
int j = 0;
for (int i = 0; i < hexLen ; i += 2 ){
result[j] = hexToByte(inHex.substring(i, i + 2));
j++;
}
return result;
}
private static byte hexToByte(String inHex) {
return (byte)Integer.parseInt(inHex,16);
}
}