Again I have some problems with hexadecimal numbers, java and byte arrays. I now 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...

And I have no idea how to convert the byte array into a string like this. It's everything in Java.

share|improve this question
3  
Why not just give it a try first and show us what you've got. You've nothing to lose and all to gain. Integer has a toHexString(...) method that may help if this is what you're looking for. Also String.format(...) can do some neat formatting tricks using the %2x code string. – Hovercraft Full Of Eels Mar 11 '12 at 13:09
right. i don't know, i'im just not capable for that today. bad day for working. vote for delete because it's pretty pointless to ask. – vlad Mar 11 '12 at 13:17

5 Answers

up vote 31 down vote accepted

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

public static String bytesToHex(byte[] bytes) {
    final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for ( int j = 0; j < bytes.length; j++ ) {
        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.

share|improve this answer
14  
I just found javax.xml.bind.DataTypeConverter, part of the standard distribution. Why doesn't this come up when you Google this kind of problem? Lots helpful tools, including String printHexBinary(byte[]) and byte[] parseHexBinary(String). printHexBinary is, however, much (2x) slower than the function in this answer. (I checked the source; it uses a stringBuilder. parseHexBinary uses an array.) Really, though, for most purposes it's fast enough and you probably already have it. – maybeWeCouldStealAVan Mar 31 '12 at 1:31

If you're not averse to including extra libraries, the commons codec library has a class for doing just this.

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

I used it just this morning in a personal project.

share|improve this answer
7  
+1 Part of the whole idea of Java is to use libraries when they exist! – Beta033 Sep 26 '12 at 21:15
2  
@Beta033 At first glance I agreed and though this was a great answer and was surprised no one else suggested it on account of its elegance and short length. Then I realized it relied on an external library - if you're not already using the library for some other reason, this is a terrible solution. -1 – ArtOfWarfare Dec 6 '12 at 14:11

Simplest solution, no external libs, no digits constants:

String bytArrayToHex(byte[] a) {
   StringBuilder sb = new StringBuilder();
   for(byte b: a)
      sb.append(String.format("%02x", b&0xff));
   return sb.toString();
}
share|improve this answer

This simple oneliner works for me
String result = new BigInteger(1, inputBytes).toString(16);

share|improve this answer
3  
This oneliner drops leading zero bytes. – Voicu Jan 17 at 0:21

I found three different ways here: http://www.rgagnon.com/javadetails/java-0596.html

The most elegant one, as he also notes, I think is this one:

static final String HEXES = "0123456789ABCDEF";
public static String getHex( byte [] raw ) {
    if ( raw == null ) {
        return null;
    }
    final StringBuilder hex = new StringBuilder( 2 * raw.length );
    for ( final byte b : raw ) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4))
            .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.