美文网首页java
【Java】byte[] 以16进制形式的输出

【Java】byte[] 以16进制形式的输出

作者: Sraindy | 来源:发表于2019-08-23 16:16 被阅读0次

byte[] 以16进制形式的输出的方法

  1. 方式一 Integer.toHexString()
 public static String printHexString(byte[] b) {
        String res = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            res += hex;
        }
        return res;
    }
  1. 方式二 formatter.format()
public static String byte2HexString(byte[] bb, int index, boolean isUpperCase) {
        if (null == bb || bb.length == 0) {
            return "";
        }
        String hexStr = "";
        String formatterStr = "%02X";
        Formatter formatter = new Formatter();
        if (isUpperCase) {
            formatterStr = "%02X";
        } else {
            formatterStr = "%02x";
        }

        for (int i = index; i < bb.length; i++) {
            hexStr = formatter.format(formatterStr, bb[i]).toString();
        }
        return hexStr;
    }

16进制形式的字符转成byte[]

public static byte[] hexStringToByte(String hex) {
        byte[] result = null;
        if (null == hex) {
            return result;
        }
        hex = hex.toUpperCase();
        final String HEX_NUMS_STR = "0123456789ABCDEF";
        int len = (hex.length() / 2);
        result = new byte[len];
        char[] hexChars = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR.indexOf(hexChars[pos + 1]));
        }
        return result;
    }

相关文章

网友评论

    本文标题:【Java】byte[] 以16进制形式的输出

    本文链接:https://www.haomeiwen.com/subject/uirtectx.html