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


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.)


Apache Commons Codec库有一个Hex类来完成这种类型的工作。

import org.apache.commons.codec.binary.Hex;

String foo = "I am a string";
byte[] bytes = foo.getBytes();
System.out.println( Hex.encodeHexString( bytes ) );

Use DatatypeConverter.printHexBinary() . You can read its documentation in http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html

For example:

byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61};
System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(bytes));

Will result in:

000086003D

As you can see this will retrieve the hexadecimal string representing the array of bytes with leading zeros.

This answer is basically the same as in the question In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

链接地址: http://www.djcxy.com/p/87086.html

上一篇: 如何在Android上使背景20%透明

下一篇: 如何在Java中将字节数组转换为十六进制字符串?