- package zxx.newer;
- import java.io.UnsupportedEncodingException;
- /**
- * 编码成unicode
- * @author zhaoxin
- * @version
- */
- class Native2Ascii {
- /**
- * 转为ascii编码
- * @param t
- * @return
- */
- public static String n2a(String t) {
- StringBuffer unicode = new StringBuffer();
- char[] charAry = new char[t.length()];
- for (int i = 0; i < charAry.length; i++) {
- charAry[i] = (char) t.charAt(i);
- unicode.append("//u" + Integer.toString(charAry[i], 16));
- }
- return unicode.toString();
- }
- /**
- * ascii转为本地码
- * @param theString
- * @return
- */
- private static String a2n(String theString) {
- char aChar;
- int len = theString.length();
- StringBuffer outBuffer = new StringBuffer(len);
- for (int x = 0; x < len;) {
- int nextCharLength=0;
- int tempInt;
- aChar = theString.charAt(x++);
- if (aChar == '//') {
- //此处for循环取得code长度
- for(tempInt=x;;tempInt++){
- if(tempInt==len || theString.charAt(tempInt)=='//'){
- break;
- }
- else{
- nextCharLength++;
- }
- }
- nextCharLength--;
- aChar = theString.charAt(x++);
- if (aChar == 'u') {
- // Read the xxxx
- int value = 0;
- for (int i = 0; i < nextCharLength; i++) {
- aChar = theString.charAt(x++);
- switch (aChar) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':value = (value << 4) + aChar - '0';break;
- case 'a':
- case 'b':
- case 'c':
- case 'd':
- case 'e':
- case 'f':value = (value << 4) + 10 + aChar - 'a';break;
- case 'A':
- case 'B':
- case 'C':
- case 'D':
- case 'E':
- case 'F':value = (value << 4) + 10 + aChar - 'A';break;
- default:
- throw new IllegalArgumentException("Malformed //uxxxx or //uxx encoding.");
- }
- }
- outBuffer.append((char) value);
- } else {
- if (aChar == 't')
- aChar = '/t';
- else if (aChar == 'r')
- aChar = '/r';
- else if (aChar == 'n')
- aChar = '/n';
- else if (aChar == 'f')
- aChar = '/f';
- outBuffer.append(aChar);
- }
- } else
- outBuffer.append(aChar);
- }
- return outBuffer.toString();
- }
- public static void main(String[] args) throws UnsupportedEncodingException {
- String ss = "暗示adsf";
- System.out.println(ss + ":/n" + n2a(ss));
- System.out.println("/nloadConvert:" + a2n(n2a(ss)));
- }
- }
java unicode编码
最新推荐文章于 2021-09-03 15:51:23 发布