如何在Java中将字节数组转换为十六进制字符串? [英] How to convert a byte array to a hex string in Java?
问题描述
我有一个用十六进制数字填充的字节数组,打印它的简单方法是毫无意义的,因为有许多不可打印的元素。我需要的是以下形式的确切十六进制代码: 3a5f771c
private final char [] hexArray = 0123456789ABCDEF .toCharArray();
public static String bytesToHex(byte [] bytes){
char [] hexChars = new char [bytes.length * 2];
for(int j = 0; j int v = bytes [j]& 0xFF的;
hexChars [j * 2] = hexArray [v>>> 4];
hexChars [j * 2 + 1] = hexArray [v&为0x0F];
}
返回新的字符串(hexChars);
}
我自己的微小基准(一千万字节,一千字节256字节,一千万字节次)显示它比任何其他选择都快得多,大约一半时间在长阵列上。与我之前的答案相比,切换到按位操作 - 如讨论中所建议的那样 - 将长阵列的时间减少了20%。 (编辑:当我说它比其他代码更快时,我的意思是讨论中提供的替代代码,性能等同于使用非常类似代码的Commons Codec。)
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 final static char[] hexArray = "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] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
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. (Edit: 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.)
这篇关于如何在Java中将字节数组转换为十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!