How to convert byte array to hex format in Java

蹲街弑〆低调 提交于 2019-11-29 03:50:40

You can use the String javax.xml.bind.DatatypeConverter.printHexBinary(byte[]). e.g.:

public static void main(String[] args) {
    byte[] array = new byte[] { 127, 15, 0 };
    String hex = DatatypeConverter.printHexBinary(array);
    System.out.println(hex); // prints "7F0F00"
}

String.format actually makes use of the java.util.Formatter class. Instead of using the String.format convenience method, use a Formatter directly:

Formatter formatter = new Formatter();
for (byte b : bytes) {
    formatter.format("%02x", b);
}
String hex = formatter.toString();

The way I do it:

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

  public static String toHexString(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for (int j = 0; j < bytes.length; j++) {
      v = bytes[j] & 0xFF;
      hexChars[j * 2] = HEX_CHARS[v >>> 4];
      hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F];
    }
    return new String(hexChars);
  }

Try this

byte[] raw = some_bytes;
javax.xml.bind.DatatypeConverter.printHexBinary(raw)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!