Java Hex Calculate toHex(byte[] data)

Here you can find the source of toHex(byte[] data)

Description

to Hex

License

Apache License

Declaration

public static String toHex(byte[] data) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static String toHex(byte[] data) {
        return toHex(data, false);
    }/*from  w  w w  .  j  ava  2  s .  co  m*/

    /**
     * Convert byte array to Hex code
     *
     * @param data
     * @param isFormat
     *            format output string: 16 byte one line, one byte is separted
     *            by space
     * @return
     */
    public static String toHex(byte[] data, boolean isFormat) {
        if (data == null || data.length == 0)
            return "";

        int tmp;
        int s1, s2;
        StringBuilder sb = new StringBuilder(data.length * 2 + (isFormat ? data.length + data.length / 16 : 0));
        for (int i = 0; i < data.length; i++) {
            tmp = data[i] & 0x000000FF;
            s1 = tmp / 16;
            s2 = tmp % 16;
            if (s1 < 10)
                sb.append((char) (s1 + 48));
            else if (s1 >= 10)
                sb.append((char) (s1 + 55));
            if (s2 < 10)
                sb.append((char) (s2 + 48));
            else if (s2 >= 10)
                sb.append((char) (s2 + 55));

            if (isFormat) {
                sb.append(" ");

                if ((i + 1) % 16 == 0)
                    sb.append("\n");
            }
        }
        return sb.toString();
    }
}

Related

  1. toHex(byte[] data)
  2. toHex(byte[] data)
  3. toHex(byte[] data)
  4. toHex(byte[] data)
  5. toHex(byte[] data)
  6. toHex(byte[] data, int bytesPerGroup)
  7. toHex(byte[] data, int length)
  8. toHex(byte[] data, int off, int len)
  9. toHex(byte[] data, int perLine, boolean offset)