Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

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

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

(我需要的是以下形式的确切十六进制代码: 3a5f771c)

  ask by Andre translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,后者使用非常相似的代码。))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...