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);
}
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.
(我自己的小型基准测试(千字节为一千个字节,十亿字节为256个字节)表明它比其他任何方法都快得多,大约是长数组的一半。)
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. (与我从中得到的答案相比,切换到按位运算-正如讨论中所建议的--长数组的时间减少了约20%。)
(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.) ((编辑:当我说它比其他方法快时,是指讨论中提供的其他代码。性能等效于Commons Codec,后者使用非常相似的代码。))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…