日期:2014-05-20 浏览次数:20963 次
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;
}
}