一串utf-8字符串怎么转换成汉字
求助:一串utf-8字符串如何转换成汉字
我在一个设备上读歌名,读回来是uft-8编码的字符串(如:313239e4b8aae5b7a5e585b72d3300),我要如何将这串字符串转换成汉字呢?
求解答,谢谢。。。。
------解决方案--------------------
写了代码,参考一下。(要求:字符串中只能有0-9和a--e,不存在其他字符。而且是偶数)。
我在一个设备上读歌名,读回来是uft-8编码的字符串(如:313239e4b8aae5b7a5e585b72d3300),我要如何将这串字符串转换成汉字呢?
求解答,谢谢。。。。
------解决方案--------------------
写了代码,参考一下。(要求:字符串中只能有0-9和a--e,不存在其他字符。而且是偶数)。
- Java code
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; } }