如何在 Java 中将字节数组转换为十六进制字符串? [英] How to convert a byte array to a hex string in Java?

查看:32
本文介绍了如何在 Java 中将字节数组转换为十六进制字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个填充有十六进制数字的字节数组,以简单的方式打印它是毫无意义的,因为有许多不可打印的元素.我需要的是以下形式的确切十六进制代码:3a5f771c

I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in the form of: 3a5f771c

推荐答案

来自讨论这里,特别是这个答案,这是我目前使用的功能:

From the discussion here, and especially this answer, this is the function I currently use:

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = HEX_ARRAY[v >>> 4];
        hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
    }
    return new String(hexChars);
}

我自己的小型基准测试(100 万次 100 万字节,1000 万次 256 字节)表明它比任何其他替代方案都快得多,大约是长数组的一半.与我从中得到的答案相比,切换到按位操作——正如讨论中所建议的——为长数组减少了大约 20% 的时间.(当我说它比替代方案更快时,我指的是讨论中提供的替代代码.性能相当于使用非常相似代码的 Commons Codec.)

My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. ( When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)

2k20 版本,关于 Java 9 压缩字符串:

2k20 version, with respect to Java 9 compact strings:

private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
public static String bytesToHex(byte[] bytes) {
    byte[] hexChars = new byte[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = HEX_ARRAY[v >>> 4];
        hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
    }
    return new String(hexChars, StandardCharsets.UTF_8);
}

这篇关于如何在 Java 中将字节数组转换为十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆