Java 打印byte[]

2020-01-09  本文已影响0人  兔宰子

代码

public static void main(String args[]) {
        System.out.println(bytesToHexString("中华人民共和国".getBytes()));
    }
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            stringBuilder.append("0x");

            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            if (i != src.length-1) {
                stringBuilder.append(",");

            }
        }
        return stringBuilder.toString();
    }

输出结果

0xe4,0xb8,0xad,0xe5,0x8d,0x8e,0xe4,0xba,0xba,0xe6,0xb0,0x91,0xe5,0x85,0xb1,0xe5,0x92,0x8c,0xe5,0x9b,0xbd
上一篇下一篇

猜你喜欢

热点阅读