Java中byte数组和16进制字符串互相转换

首先,byte数组转成16进制字符串:

/**
     * byte数组转成字符串
     *
     * @param bytes     数组
     * @param isCaptial 使用大写还是小写表示
     * @return 转换后的字符串
     */
public static String bytesToHexStr(byte[] bytes, boolean isCaptial) {
        if (null == bytes || bytes.length <= 0) {
            return null;
        }
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            if (isCaptial) {
            //02表示使用2位16进制字符表示当前的byte数据,X或者x表示16进制字符串
                s.append(String.format("%02X", bytes[i]));
            } else {
                s.append(String.format("%02x", bytes[i]));
            }
        }
        return s.toString();
    }

然后,将16进制字符串转成byte数组:

public static byte[] hexStrToBytes(String hex) {
        if (null == hex || hex.equals("")) {
            return null;
        }
        int strLength = hex.length();//获取16进制字符串长度
        int length = strLength / 2; //获取字节长度
        char[] hexChars;//用来存放字符串转换成的字符数组
        if (length * 2 < strLength) { // strLength is odd, add '0'
            length += 1;
            hexChars = ("0" + hex).toCharArray();
        } else {
            hexChars = hex.toCharArray();
        }
        byte[] bytes = new byte[length];//用来存放最终组成的数组
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            //组成1字节的数据。因为是需要两个字符组成一个字节的数据,这就需要第一个字符向左移4位。
            bytes[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return bytes;
    }

public static byte charToByte(char c) {
        byte result = (byte) "0123456789abcdef".indexOf(c);
        if (result == -1) {
            return (byte) "0123456789ABCDEF".indexOf(c);
        } else {
            return result;
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值