日期:2014-05-20  浏览次数:20943 次

16进制字符串如何存入byte数组
String s="0x00";
byte[] b=new byte[10];
b[0]=??????

如果我b[0]要等于0x00应该怎么做?

------解决方案--------------------
byte[] b = s.getBytes();
或byte[] b = s.getBytes("UTF-8");
------解决方案--------------------
探讨
String s="0x00";
byte[] b=new byte[10];
b[0]=??????

如果我b[0]要等于0x00应该怎么做?

------解决方案--------------------
Java code
    //输入一个字符串,返回一个长度为2 的字节数组. 
    //输入的数组正确的话,byte2[0]=0;byte[1]为字符串的值。
    //否则,如果给定的字符串不正确,比如"0xt","ff","0xf33" 等等,
    // byte2[0]=1。
    //
    public static byte[] hexStringToValue(String str1)    
    {
        byte[] byte2={0,0};
        int number=0;
        char h='0',l='0';                    //h 为16分位的字符。l是个位的。
        if(str1.length()<3||str1.length()>4||str1.charAt(0)!='0'
                ||str1.charAt(1)!='x')            //字符串长度要么3个,要么4个。其他不正确。
        {
            byte2[0]=1;
            return byte2;
        }
        String newStr=str1.substring(2);            //去掉"0x"。
        //获得16分位和个位上的字符

        if(newStr.length()==1)                    // 只1位数 0-f.(字符串长度3)。
        {
            h='0';                        //16分位补零。(00-0f).
            l=newStr.charAt(0);                //把个位数的字符付给l.
        }
        else                            //字符串4个长。
        {
            h=newStr.charAt(0);
            l=newStr.charAt(1);
        }

        //判断16分位的字符是否有效,对有效的计算其10进制值。
        //
        if(h<'0'||(h>'9'&&h<'A')||(h>'F'&&h<'a')||h>'f')        //剔除不正确的字符.
        {
            byte2[0]=1;
            return byte2;
        }
        else if(h<='9')                            //16分位为0-9,
        {
            number=(h-'0')*16;
        }
        else if(h<='F')                            //16分位 A-F.
        {
            number=((h-'A')+10)*16;        
        }
        else                                //16分位 a--f.
        {
            number=((h-'a')+10)*16;
        }
        //判断个位的有效性,对有效的计算10进制值。
        //
        if(l<'0'||(l>'9'&&l<'A')||(l>'F'&&l<'a')||l>'f')
        {
            byte2[0]=1;
            return byte2;
        }
        else if(l<='9')                            //个位是0--9。
        {
            number+=(l-'0');
        }
        else if(l<='F')                            //个位是A--F.(相当于10-15)。
        {
            number+=(l-'A')+10;
        }
        else                                //个位是a--f(相当于10-15)。
        {                                
            number+=(l-'a')+10;                    
        }

        byte b=(byte)number;
        byte2[1]=b;
        return byte2;
    }

------解决方案--------------------
byte[] b= "0x00".getBytes();
System.out.println(b[0]);
不知道lZ是这个意思吗
------解决方案--------------------
Java code

     String string = "0x0f";
     String numStr = string.substring(2);
     System.out.println(Byte.valueOf(numStr, 16));

------解决方案--------------------
Java code

b[0] = (byte)0x00