Is there a simpliest way of doing this?

Posted by Tom Brito on Stack Overflow See other posts from Stack Overflow or by Tom Brito
Published on 2010-04-15T14:05:58Z Indexed on 2010/04/15 14:13 UTC
Read the original article Hit count: 200

Filed under:
|
|

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 0C 0A" (without the spaces)

© Stack Overflow or respective owner

Related posts about java

Related posts about hex