2024/Java字符串和16进制数转换
import java.io.IOException;
public class HeStrTest {
public static void main(String[] args) throws IOException {
String he = string2Unicode("汉字123abcAb!@slc");
System.out.println(he);
System.out.println("=====16进制========");
he =strTo16(he);
System.out.println(he);
System.out.println("-------------------------");
System.out.println("16转字符串");
he = hexStringToString(he);
System.out.println(he);
System.out.println("unicode转文字11111111111111111");
he =unicode2String(he);
System.out.println(he);
}
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
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) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "UTF-8");
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
/**
* 字符串转换unicode
*/
public static String string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
// 取出每一个字符
char c = string.charAt(i);
// 转换为unicode
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
/**
* unicode 转字符串
*/
public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
// 转换出每一个代码点
int data = Integer.parseInt(hex[i], 16);
// 追加成string
string.append((char) data);
}
return string.toString();
}
/**
* 字符串转化成为16进制字符串
* @param s
* @return
*/
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
}