Snippet IT IT News, Programming, Internet and Blogging

22May/090

Java: Format Bytes Array into Hexadecimal String

ADVERTISEMENTS

Sometimes, we may want to format a bytes array into hexadecimal (base-16) format for debugging purpose or for better readability. One byte has 8 bits and one byte can be represent by two hexadecimal characters (0 - 15 and A - F).

You can use the Java's String.format to print out each byte but I still prefer my own way of doing it, which I believe it will perform a little bit faster. The following code shows the way to convert bytes array into hexadecimal string and vice versa.

 

public class Bytes {

  private final static char[] HEX = {
    '0', '1', '2', '3', '4', '5', '6', '7',
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String toHex(byte[] bytes) {
    StringBuilder buffer;

    buffer = new StringBuilder();
    for (byte b : bytes) {
      buffer.append(HEX[(b >> 4) & 0xf]);
      buffer.append(HEX[b & 0xf]);
    }
    return buffer.toString();
  }

  public static byte[] fromHex(String hex) throws NumberFormatException {
    char[] chars;
    char c;
    int i;
    int j;
    byte[] bytes;
    byte b;

    chars = hex.toUpperCase().toCharArray();

    if (chars.length % 2 != 0) {
      throw new NumberFormatException("Incomplete hex value");
    }

    bytes = new byte[chars.length / 2];
    b = 0;
    j = 0;
    for (i = 0; i < chars.length; i++) {
      c = chars[i];
      if (c >= '0' && c <= '9') {
        b = (byte) ((b << 4) | (0xff & (c - '0')));
      } else if (c >= 'A' && c <= 'F') {
        b = (byte) ((b << 4) | (0xff & (c - 'A' + 10)));
      } else {
        throw new NumberFormatException("Invalid hex character: " + c);
      }
      if ((i + 1) % 2 == 0) {
        bytes[j++] = b;
        b = 0;
      }
    }

    return bytes;
  }
}

Related Articles

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.