public class TestHex {
public static String toHexString(byte[] value,int start,int len) {
if (value == null ) return null;
String newString = "";
for (int i = start; i < start + len; i++) {
byte b = value[i];
String str = Integer.toHexString(b);
if (str.length() > 2) {
str = str.substring(str.length() - 2);
}
if (str.length() < 2) {
str = "0" + str;
}
newString += str + " ";
}
return newString.toUpperCase();
}
public static byte[] hexToBytes(String hexString) {
if (hexString == null) return null;
hexString = hexString.replaceAll(" ", "");
byte[] bytes = new byte[hexString.length()/2];
for (int i=0; i<bytes.length; i++) {
bytes[i] = (byte)Integer.parseInt(hexString.substring(i*2, i*2+2), 16);
}
return bytes;
}
public static byte[] hexToBytes1(String hexString) {
String[] temp = hexString.split(" ");
byte[] bytes = new byte[temp.length];
for(int i=0;i<temp.length;i++){
bytes[i] = (byte)Integer.parseInt(temp[i], 16);
}
return bytes;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String temp = "我测试";
byte[] temp1 = temp.getBytes();
String a = toHexString(temp1,0,temp1.length);
System.out.println(a);
byte[] temp2 = hexToBytes(a);
String b = new String(temp2);
System.out.println(b);
byte[] temp3 = hexToBytes1(a);
String c = new String(temp3);
System.out.println(c);
}
}
结果:
E6 88 91 E6 B5 8B E8 AF 95
我测试
我测试