前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java十六进制和byte数组转换

Java十六进制和byte数组转换

作者头像
sunonzj
发布2022-06-21 10:19:52
1K0
发布2022-06-21 10:19:52
举报
文章被收录于专栏:zjblogzjblog

byte数组转16进制

代码语言:javascript
复制
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数组

代码语言:javascript
复制
/**
 * 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进制

代码语言:javascript
复制
strSerial = bytes2hexStr(struOut.byData);
System.out.println(strSerial);
Long.parseLong(strSerial, 16)
System.out.println("读卡成功,内容为" + Long.parseLong(strSerial, 16));
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-11-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档