字符串、bute[]数组和十六进制字符串的相互转换

时间:2022-06-15 17:53:51
1、字符串转换成十六进制字符串
public static String str2HexStr(String str) {
        if (EncodingUtil.isEmpty(str)) {
            return "";
        }
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = new byte[0];
        try {
            bs = str.getBytes("GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString();
    }

2、16进制字符串转换为byte数组

public static byte[] hexStringToBytes2(String hexString) {
        if (hexString == null) {            // 判断源字符串是否为空
            return null;
        }
        String tmp = "0123456789ABCDEF";
        char[] hexChars = hexString.toCharArray();
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];    // 创建字节数组空间

        for (int i = 0; i < len; i += 2) {    //
            bytes[i / 2] = (byte) ((tmp.indexOf(hexChars[i]) << 4) | tmp.indexOf(hexChars[i + 1]));
        }
        return bytes;
    }

 

 3、byte[]数组转换为16进制字符串

    public static String bytesToHexString(byte[] bytes) {
        if (bytes == null)
            return null;
        StringBuffer stringBuffer = new StringBuffer(bytes.length * 2);
        for (byte b : bytes) {
            if ((b & 0xFF) < 0x10) {
                stringBuffer.append('0');
            }
            stringBuffer.append(Integer.toHexString(0xFF & b));
        }

        return stringBuffer.toString().toUpperCase(Locale.getDefault());
    }