Java codepublic class StringToUnicode
{
public static void main(String[] args) throws Exception
{
String str="中文编码";
str=str.replace("",""); //去掉多余的字符。""
str=str.replace(";",""); //去掉";"
String UnicodeString=null;
UnicodeString=stringToUnicode(str);
System.out.println(UnicodeString);
}
//把字符串转换成Unicode字符串,输入的字符串中只能是0-9数字或者是A--F字母,不能有任何其他字符
//输入字符串要是偶数个字符。
public static String stringToUnicode(String str) throws Exception
{
byte[] bytes=new byte[str.length()/2+2]; //定义字节数组,长度为字符串的一半。加 2 是存放unicode 编码头(ff,fe)
bytes[0]=-2; //-2 对应fe,-1对应ff. 后面要交换,所以保存 fe,ff.
bytes[1]=-1;
byte tempByte=0; //临时变量。
byte tempHigh=0;
byte tempLow=0;
for(int i=0,j=2;i
{
tempByte=(byte)(((int)str.charAt(i))&0xff); //处理高位。
if(tempByte>=48&&tempByte<=57)
{
tempHigh=(byte)((tempByte-48)<<4); //'0'对应48。
}
else if(tempByte>=65&&tempByte<=70) //'A'--'F'
{
tempHigh=(byte)((tempByte-65+10)<<4);
}
tempByte=(byte)(((int)str.charAt(i+1))&0xff); //处理低位。
if(tempByte>=48&&tempByte<=57)
{
tempLow=(byte)(tempByte-48);
}
else if(tempByte>=65&&tempByte<=70) //'A'--'F'
{
tempLow=(byte)(tempByte-65+10); //'A'对应10.(或0xa.)
}
bytes[j]=(byte)(tempHigh|tempLow); //通过‘或’加在一起。
}
for(int i=0;i
{
byte b1=bytes[i];
bytes[i]=bytes[i+1];
bytes[i+1]=b1;
}
String result=new String(bytes,"Unicode");
return result;
}
}