日期:2014-05-20 浏览次数:20919 次
public class StringToUtf8
{
public static void main(String[] args) throws Exception
{
String str="313239e4b8aae5b7a5e585b72d3300";
String utf8String=null;
utf8String=stringToUtf(str);
System.out.println(utf8String);
}
//把字符串转换成utf8字符串,输入的字符串中只能是0-9数字或者是a--e字母,不能有任何其他字符
//输入字符串要是偶数个字符。
public static String stringToUtf(String str) throws Exception
{
byte[] bytes=new byte[str.length()/2]; //定义字节数组,长度为字符串的一半。
byte tempByte=0; //临时变量。
byte tempHigh=0;
byte tempLow=0;
for(int i=0,j=0;i<str.length();i+=2,j++) //每循环处理2个字符,最后新城一个字节。
{
tempByte=(byte)(((int)str.charAt(i))&0xff); //处理高位。
if(tempByte>=48&&tempByte<=57)
{
tempHigh=(byte)((tempByte-48)<<4);
}
else if(tempByte>=97&&tempByte<=101)//'a'--'e'
{
tempHigh=(byte)((tempByte-97+10)<<4);
}
tempByte=(byte)(((int)str.charAt(i+1))&0xff); //处理低位。
if(tempByte>=48&&tempByte<=57)
{
tempLow=(byte)(tempByte-48);
}
else if(tempByte>=97&&tempByte<=101) //'a'--'e'
{
tempLow=(byte)(tempByte-97+10); //'a'对应10.(或0xa.)
}
bytes[j]=(byte)(tempHigh|tempLow); //通过‘或’加在一起。
}
String result=new String(bytes,"UTF8");
return result;
}
}