欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java byte数组和16进制互转 非原创

程序员文章站 2024-03-16 23:44:16
...

 byte数组转16进制

public static String byte2hex(byte[] b){
    StringBuffer sb = new StringBuffer();
    String stmp = "";
    for (int n = 0; n < b.length; n++) {
        stmp = Integer.toHexString(b[n] & 0XFF);
        if (stmp.length() == 1) {
            sb.append("0" + stmp);
        } else {
            sb.append(stmp);
        }
    }
    return sb.toString();
 }

16进制转byte数组

public static byte[] hex2byte(String str) {
    if (str == null)
        return null;
    str = str.trim();
    int len = str.length();
    if (len == 0 || len % 2 == 1)
        return null;
    byte[] b = new byte[len / 2];
    try {
        for (int i = 0; i < str.length(); i += 2) {
            b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();
        }
        return b;
    } catch (Exception e) {
        return null;
    }
  }

 

相关标签: java