当前位置: 代码迷 >> J2SE >> 需要幫助~string與char的轉換
  详细解决方案

需要幫助~string與char的轉換

热度:8602   发布时间:2013-02-25 00:00:00.0
急需幫助~string與char的轉換
我想把string變成16進位char
ex: string a="000000010203"
變成 char b={0x00,0x00,0x00,0x01,0x02,0x03}
誰可以教教我嗎~謝謝


------解决方案--------------------------------------------------------
那试试这个,转成了字符(char)数组:
Java code
import java.util.Arrays;                    //引入包为显示数组方便。public class StringToChar{    public static void main(String[] args) throws Exception    {        String str="000000010203";        char[] result=stringToChar(str);        // 调用转换函数。        System.out.println(Arrays.toString(result));    }        //把字符串转换成char数组字符串,输入的字符串中只能是0-9数字或者是A--F字母,或者a-f不能有任何其他字符    //输入字符串要是偶数个字符。    public static char[] stringToChar(String str)    {        char[] chars=new char[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);    //'0'对应48。            }            else if(tempByte>=65&&tempByte<=70)        //'A'--'F'             {                tempHigh=(byte)((tempByte-65+10)<<4);            }            else                        //'a'--'f'.            {                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>=65&&tempByte<=70)        //'A'--'F'            {                tempLow=(byte)(tempByte-65+10);        //'A'对应10.(或0xa.)            }            else            {                tempLow=(byte)(tempByte-97+10);        //'a' -'f'            }            chars[j]=(char)((tempHigh|tempLow)&0xff);        //通过‘或’加在一起。并转换.        }        return chars;    }}
  相关解决方案