public static byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] byteArray = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
char c = hexString.charAt(i);
int digit1 = Character.digit(c, 16);//取出相应
int number = digit1 << 4;
char c1 = hexString.charAt(i + 1);
int digit = Character.digit(c1, 16);
byteArray[i / 2] = (byte) (number + digit);
}
return byteArray;
}
/**
* ascii 转十六进制
* @param str 字符串
* @return
*/
public static String stringToHex(String str) {
StringBuffer stringBuffer = new StringBuffer(str.length() * 2);
for (int i = 0; i < str.length(); i++) {
int number = (int) str.charAt(i);
int lowNibble = number % 16;//底四位
int highNibble = number >> 4;//高四位
stringBuffer.append(getHexDigit(highNibble));
stringBuffer.append(getHexDigit(lowNibble));
}
return stringBuffer.toString();
}
/**
* 中文转十六进制
* @param str 字符串
* @return
*/
public static String chineseToHex(String str) {
StringBuilder hexStringBuilder = new StringBuilder();
char[] chars = str.toCharArray();
for (char value : chars) {
String result = Integer.toHexString(value);
result = result.length() % 2 == 0 ? result : "0" + result;
hexStringBuilder.append(result);
}
return hexStringBuilder.toString();
}
/**
* 获取十六进制数字
* @param value
* @return
*/
private static char getHexDigit(int value) {
if (value >= 0 && value <= 9) {
return (char) ('0' + value);
} else {
return (char) ('A' + (value - 10));
}
}
/**
* 中文转十六进制
* @param str
* @return
*/
private static String decimalToHex(String str) {
StringBuilder hexBuilder1 = new StringBuilder();
char[] chars = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
StringBuilder hexBuilder = new StringBuilder();
int decimal = (int) chars[i];
while (decimal != 0) {
int remainder = decimal % 16;
hexBuilder.insert(0, getHexDigit(remainder));
decimal = decimal / 16;
}
if (hexBuilder.length() % 2 != 0) {
hexBuilder.insert(0, '0');
}
hexBuilder1.append(hexBuilder);
}
return hexBuilder1.toString();
}