Asciiとnative間の変換
2143 ワード
package com.test;
public class AsciiToString {
public static void main(String argv[]) {
AsciiToString tt = new AsciiToString();
String str1 = tt.native2ascii(" , 。");
System.out.println("native2ascii:"+str1);
String str2 = tt.ascii2native(str1);
System.out.println("ascii2native:"+str2);
}
public String native2ascii(String str) {
char ac[] = str.toCharArray();
int len = ac.length;
StringBuffer out = new StringBuffer();
for (int i = 0; i < len; i++)
if (ac[i] > '\177') {
out.append(new char[] { 92, 117 });
String s1 = Integer.toHexString(ac[i]);
StringBuffer stringbuffer = new StringBuffer(s1);
stringbuffer.reverse();
int l = 4 - stringbuffer.length();
for (int i1 = 0; i1 < l; i1++)
stringbuffer.append('0');
for (int j1 = 0; j1 < 4; j1++)
out.append(stringbuffer.charAt(3 - j1));
} else {
out.append(ac[i]);
}
return out.toString();
}
public String ascii2native(String str) {
char[] ac1 = str.toCharArray();
int k = ac1.length;
StringBuffer sb = new StringBuffer();
int k1 = 0;
do {
if (k1 >= k)
break;
char c = ac1[k1++];
if (c != '\\' || k - k1 < 5) {
sb.append(c);
continue;
}
c = ac1[k1++];
if (c != 'u') {
sb.append('\\');
sb.append(c);
} else {
char c1 = '\0';
boolean flag2 = true;
try {
c1 = (char) Integer.parseInt(new String(ac1, k1, 4), 16);
} catch (NumberFormatException numberformatexception) {
flag2 = false;
}
if (flag2) {
sb.append(c1);
k1 += 4;
} else {
sb.append('\\');
sb.append(c);
}
}
} while (true);
return sb.toString();
}
}