1.计算机只会知道010101的二进制,到底层10进制和16进制还是会转成位数被识别,所以可以通过byte数组去进行转换
private byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase(Locale.getDefault());
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] data = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
data[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return data;
}
// 获取字符串对应的16进制数
private byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
// 转换HEX为字符串
private String changeHexToString(final byte[] buffer, final int size) {
StringBuffer strbuf = new StringBuffer("");
if (buffer == null || buffer.length <= 0) {
return null;
}
for (int i = 0; i < size; i++) {
int temp = buffer[i] & 0xFF;
String strTemp = Integer.toHexString(temp);
if (strTemp.length() < 2) {
strbuf.append(0);
}
strbuf.append(strTemp);
}
return strbuf.toString();
}