下午同事说要一个Native2Ascii和Ascii2Native的Java实现,Google了半天发现有的是错误的实现,有的只有Native2Ascii没有Ascii2Native,有的又是其他语言实现的,干脆自己参考着写了一个。
package
/**
* native2ascii.exe Java code implementation.
*
* @author
* @version 1.0
*/
public class
/**
* prefix of ascii string of native character
*/
private static String PREFIX = "\\u";
/**
* Native to ascii string. It's same as execut native2ascii.exe.
*
* @param str
* native string
* @return ascii string
*/
public static
char[] chars = str.toCharArray();
new
for (int i = 0; i < chars.length; i++) {
sb.append(char2Ascii(chars[i]));
}
return
}
/**
* Native character to ascii string.
*
* @param c
* native character
* @return ascii string
*/
private static String char2Ascii(char
if (c > 255) {
new
sb.append(PREFIX);
int code = (c >> 8);
String tmp = Integer.toHexString(code);
if (tmp.length() == 1) {
"0");
}
sb.append(tmp);
0xFF);
tmp = Integer.toHexString(code);
if (tmp.length() == 1) {
"0");
}
sb.append(tmp);
return
else
return
}
}
/**
* Ascii to native string. It's same as execut native2ascii.exe -reverse.
*
* @param str
* ascii string
* @return native string
*/
public static
new
int begin = 0;
int
while (index != -1) {
sb.append(str.substring(begin, index));
6)));
6;
index = str.indexOf(PREFIX, begin);
}
sb.append(str.substring(begin));
return
}
/**
* Ascii to native character.
*
* @param str
* ascii string
* @return native character
*/
private static char
if (str.length() != 6) {
throw new
"Ascii string of a native character must be 6 character.");
}
if (!PREFIX.equals(str.substring(0, 2))) {
throw new
"Ascii string of a native character must start with \"\\u\".");
}
2, 4);
int code = Integer.parseInt(tmp, 16) << 8;
4, 6);
16);
return (char) code;
}
}