16进制字符串与byte数组互转

16进制字符串与byte数组互转

public class Test1 {

    private static String hexSrc = "01 DA 20 C9 38 57";
    private static byte[] bytes = { 0x01, (byte)0xDA, 0x20, (byte)0xC9, 0x38, 0x57 };

    public static void main(String[] args) {
        System.err.println(hexSrc.trim().replaceAll("\\s*", ""));
        System.err.println(bytes2HexString(hexStringToBytes(hexSrc)));
                            //hexStringToBytes(hexSrc)方法转换出来的效果和bytes的格式一样
        System.err.println(bytesToHexString(bytes));

    }

    /**
     * 将byte数组转化为16进制字符串
     * string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。
     */
    public static String bytesToHexString(byte[] bs) {
        StringBuffer sb = new StringBuffer();
        if (bs == null) {
            return null;
        }

        for (int i = 0; i < bs.length; i++) {
            // Integer.toHexString(int)来转换成16进制字符串
            String hex = Integer.toHexString(bs[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase()); // 将小写字母转化为大写
        }

        return sb.toString();
    }

    /**
     * 将16进制字符串转换为byte数组
     * 
     * @param 需要转换的16进制字符串
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.trim().replaceAll("\\s*", ""); // 去除字符串中的空格

        String hexFormat = "0123456789ABCDEF";

        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) (hexFormat.indexOf(hexChars[pos]) << 4 | hexFormat
                    .indexOf(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * 将byte数组转化为16进制字符串
     */
    public static String bytes2HexString(byte[] bytes) {
        int len = bytes.length;
        StringBuffer sb = new StringBuffer();
        char temp;
        for (int i = 0; i < len; i++) {
            temp = (char) ((bytes[i] >> 4) & 0x0F);
            sb.append((char) (temp > 9 ? (temp + 'A' - 10) : temp + '0'));
            temp = (char) (bytes[i] & 0x0F);
            sb.append((char) (temp > 9 ? (temp + 'A' - 10) : temp + '0'));
        }
        return sb.toString();
    }

}

打印效果

16进制字符串与byte数组互转_第1张图片

你可能感兴趣的:(笔记)