天天看點

把十六進制的位串轉化為byte數組

方式一:

把十六進制的位串轉化為byte數組

/**  

     * convert hex string to byte[]  

     * @param hexstring the hex string  

     * @return byte[]  

     */    

    public static byte[] hexstringtobytes(string hexstring) {    

        if (hexstring == null || hexstring.equals("")) {    

            return null;    

        }    

 if(hexstring.length()%2!=0){    

            throw new runtimeexception("hex  bit string length must be even");    

        }   

        hexstring = hexstring.touppercase();    

        int length = hexstring.length() / 2;    

        char[] hexchars = hexstring.tochararray();    

        byte[] d = new byte[length];    

        for (int i = 0; i < length; i++) {    

            int pos = i * 2;    

            d[i] = (byte) (chartobyte(hexchars[pos]) << 4 | chartobyte(hexchars[pos + 1]));    

        return d;    

    }    

/** 

     * convert char to byte 

     * 'f'-->15 

     * @param c 

     *            char 

     * @return byte 

     */  

    private static byte chartobyte(char c) {  

        int index = "0123456789abcdef".indexof(c);  

        if (index == -1) {  

            index = "0123456789abcdef".indexof(c);  

        }  

        return (byte) index;  

    }  

方式二:

把十六進制的位串轉化為byte數組

// 從十六進制字元串到位元組數組轉換  

     public static byte[] hexstring2bytes(string hexstr) {  

        int length=hexstr.length();  

        if(length%2!=0){  

            throw new runtimeexception("hex  bit string length must be even");  

        byte[] b = new byte[hexstr.length() / 2];  

        int j = 0;  

        for (int i = 0; i < b.length; i++) {  

            char c0 = hexstr.charat(j++);  

            char c1 = hexstr.charat(j++);  

            b[i] = (byte) ((parse(c0) << 4) | parse(c1));  

        return b;  

      private static int parse(char c) {  

          if (c >= 'a')  

           return (c - 'a' + 10) & 0x0f;  

          return (c - '0') & 0x0f;  

      }  

 注意:當十六進制位串轉化為位元組數組時,十六進制位串的位數必須是偶數的,因為兩個十六進制位串對應一個位元組