16进制数据转字符串string
public String hexToString(String hex) {
String result = hex;
if (!(hex.indexOf(":") == -1)) {
String[] temps = hex.split(":");
byte[] bs = new byte[temps.length];
try {
for (int j = 0; j < temps.length; j++) {
// 转换byte[]
bs[j] = (byte) Integer.parseInt(temps[j], 16);
}
// 转换String,这里编码是utf-8,可设置,根据发snmp的编码集来
// result = new String(bs, "utf-8");
result = new String(bs, "gb2312");
} catch (Exception e) {
// 一些字符不能转16进制,返回原内容
return result;
}
}
return result;
}
字符串string转16进制数据
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString().trim();
}