天天看點

字元數組和16進制互換

//字元數組轉換16進制

public static String bytes2HexString(byte[] b) {

        String r = "";

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

            String hex = Integer.toHexString(b[i] & 0xFF);

            if (hex.length() == 1) {

                hex = '0' + hex;

            }

            r += hex.toUpperCase();

        }

        return r;

    }

    private static byte charToByte(char c) {

        return (byte) "0123456789ABCDEF".indexOf(c);

     }

    public static byte[] hexString2Bytes(String hex) {

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

                return null;

            }

            else if (hex.length()%2 != 0){

                return null;

            }

            else{                

                hex = hex.toUpperCase();

                int len = hex.length()/2;

                byte[] b = new byte[len];

                char[] hc = hex.toCharArray();

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

                    int p=2*i;

                    b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p+1]));

                }

              return b;

            }           

    }

繼續閱讀