Java十六进制和byte数组转换

查看我的博客:https://www.zjhuiwan.cn 

byte数组转16进制
 private static final char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};


/*
 * byte[]数组转十六进制
 */
public static String bytes2hexStr(byte[] bytes) {
    int len = bytes.length;
    if (len == 0) {
        return null;
    }
    char[] cbuf = new char[len * 2];
    for (int i = 0; i < len; i++) {
        int x = i * 2;
        cbuf[x] = HEX_CHARS[(bytes[i] >>> 4) & 0xf];
        cbuf[x + 1] = HEX_CHARS[bytes[i] & 0xf];
    }
    return new String(cbuf);
}

16进制转byte数组

    /**
     * hex字符串转byte数组
     *
     * @param inHex 待转换的Hex字符串
     * @return 转换后的byte数组结果
     */
    public static byte[] hexToByteArray(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            // 奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            // 偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

16进制转10进制

strSerial = bytes2hexStr(struOut.byData);

System.out.println(strSerial);
makeDevice(lUserID, "2", "1", "3", "2");
System.out.println("读卡成功,内容为" + Long.parseLong(strSerial, 16));

 

16进制补足32位

while (cardNo.length() < 32) {
    cardNo = "0" + cardNo;
}
if (cardNo.length() > 32) {
    cardNo = cardNo.substring(0, 16);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值