*字符串轉化為Unicode編碼:
/**
* 字符串轉換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();
}
*字符串轉為16進制
/**
* 字符串轉化成為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;
}
*16進制轉為字符串
/**
* 16進制轉換成為string類型字符串
* @param s
* @return
*/
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");
new String();
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
*Unicode轉為字符串
/**
* 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進制
1 /**
2 * 字符串轉換成為16進制(無需Unicode編碼)
3 * @param str
4 * @return
5 */
6 public static String str2HexStr(String str) {
7 char[] chars = "0123456789ABCDEF".toCharArray();
8 StringBuilder sb = new StringBuilder("");
9 byte[] bs = str.getBytes();
10 int bit;
11 for (int i = 0; i < bs.length; i++) {
12 bit = (bs[i] & 0x0f0) >> 4;
13 sb.append(chars[bit]);
14 bit = bs[i] & 0x0f;
15 sb.append(chars[bit]);
16 // sb.append(' ');
17 }
18 return sb.toString().trim();
19 }
*16進制轉為字符串
1 /**
2 * 16進制直接轉換成為字符串(無需Unicode解碼)
3 * @param hexStr
4 * @return
5 */
6 public static String hexStr2Str(String hexStr) {
7 String str = "0123456789ABCDEF";
8 char[] hexs = hexStr.toCharArray();
9 byte[] bytes = new byte[hexStr.length() / 2];
10 int n;
11 for (int i = 0; i < bytes.length; i++) {
12 n = str.indexOf(hexs[2 * i]) * 16;
13 n += str.indexOf(hexs[2 * i + 1]);
14 bytes[i] = (byte) (n & 0xff);
15 }
16 return new String(bytes);
17 }

