前些天想要抓包分析,抓下来的包都是16进制文本,想要复制过来转化成真正的二进制分析。于是写了下面的程序:
package com.yajun;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 将16进制字符串转换为二进制数据存入文本
*
* @author yajun.wuyj
*/
public class IntegerDeocde {
public static void main(String[] args) throws IOException {
FileOutputStream fo = new FileOutputStream(new File("IntegerDecode"));
String s = "68 65 6c 6c 6f 20 77 6f 72 6c 64 2c ca c0 bd e7 c6 bd ba e2 ";
for (int i = 0; i < s.length(); i++) {
i = findNextNotBlank(s, i);
if (i == -1) {
break;
}
byte hiByte = Byte.decode("0x" + s.charAt(i)).byteValue();
i = findNextNotBlank(s, ++i);
if (i == -1) {
break;
}
byte lowByte = Byte.decode("0x" + s.charAt(i)).byteValue();
byte result = (byte) ((hiByte << 4) | lowByte);
fo.write(result);
}
fo.close();
}
// 查找下一个不为空白char
private static int findNextNotBlank(String s, int i) {
while (i < s.length() && s.charAt(i) == ' ') {
++i;
}
if (i >= s.length()) {
return -1;
}
return i;
}
}