views:

146

answers:

6

Is there a simpler way of implement this? Or a implemented method in JDK or other lib?

/**
 * Convert a byte array to 2-byte-size hexadecimal String.
 */
public static String to2DigitsHex(byte[] bytes) {
String hexData = "";
for (int i = 0; i < bytes.length; i++) {
    int intV = bytes[i] & 0xFF; // positive int
    String hexV = Integer.toHexString(intV);
    if (hexV.length() < 2) {
    hexV = "0" + hexV;
    }
    hexData += hexV;
}
return hexData;
}

public static void main(String[] args) {
System.out.println(to2DigitsHex(new byte[] {8, 10, 12}));
}

the output is: "08 0A 0C" (without the spaces)

+6  A: 

Use at least StringBuilder#append() instead of stringA += stringB to improve performance and save memory.

public static String binaryToHexString(byte[] bytes) {
    StringBuilder hex = new StringBuilder(bytes.length * 2);
    for (byte b : bytes) {
        b &= 0xff;
        if (b < 0x10) hex.append("0");
        hex.append(Integer.toHexString(b));
    }
    return hex.toString();
}
BalusC
+5  A: 

Apache Commons-Codec has the Hex class, which will do what you need:

String hexString = Hex.encodeHexString(bytes);

By far the easiest method. Don't mess with binary operators, use the libraries to do the dirty work =)

Jason Nichols
+1  A: 
public static String to2DigitsHex(final byte[] bytes) {
    final StringBuilder accum = new StringBuilder(bytes.length * 2);
    for (byte b : bytes) {
      b &= 0xff;
      if (b < 16) accum.append("0");
      accum.append(Integer.toHexString(b);
    }
    return accum.toString();
}

You're better off using an explicit StringBuilder of your own if this routine is going to be called a lot.

Pointy
+1  A: 

You could use BigInteger for this.

Example:

(new BigInteger(1,bytes)).toString(16)

You will need to add an '0' at the beginning.

A more elegant solution (taken from here) is:

BigInteger i = new BigInteger(1,bytes);
System.out.println(String.format("%1$06X", i));

You need to know the number of bytes in advance in order to use the correct formatter.

kgiannakakis
That's indeed a nice oneliner (+1), but I've profiled it before, it's relatively slow and, above all, it doesn't prefix bytes < 0x10 with zeroes.
BalusC
Only the first zero will not be prefixed. For example {8, 10, 12} will be converted to 80a0c. I have successfully used this for generation of MD5 hashes. I can't say anything about the performance.
kgiannakakis
+1  A: 
 private static String to2DigitsHex(byte[] bs) {
      String s = new BigInteger(bs).toString(16);
      return s.length()%2==0? s : "0"+s;
 }
Michael Borgwardt
A: 
hbunny