十六进制和二进制相互转换
程序员文章站
2024-03-16 22:34:40
...
//十六进制string转二进制byte[]
public static byte[] hexStringToByte(String s) {
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
System.out.println("十六进制转byte发生错误!!!");
e.printStackTrace();
}
}
return baKeyword;
}
//二进制byte[]转十六进制string
public static String byteToHexString(byte[] bytes){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String strHex=Integer.toHexString(bytes[i]);
if(strHex.length() > 3){
sb.append(strHex.substring(6));
} else {
if(strHex.length() < 2){
sb.append("0" + strHex);
} else {
sb.append(strHex);
}
}
}
return sb.toString();
}