Java Hex Calculate toHexString(byte[] bytes)

Here you can find the source of toHexString(byte[] bytes)

Description

to Hex String

License

Open Source License

Declaration

public static String toHexString(byte[] bytes) 

Method Source Code

//package com.java2s;

public class Main {
    public static String toHexString(byte[] bytes) {
        return toHexString(bytes, 8);
    }//from   www. j av  a 2 s .c  o m

    public static String toHexString(byte[] bytes, int bytesPerRow) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i += bytesPerRow) {
            int length = bytes.length - i >= bytesPerRow ? bytesPerRow : bytes.length % bytesPerRow;
            byte[] row = new byte[bytesPerRow];
            System.arraycopy(bytes, i, row, 0, length);

            for (int j = 0; j < length; j++) {
                sb.append('0');
                sb.append('x');
                sb.append(toHexString(row[j]));
                sb.append(' ');
            }

            for (int j = 0; j < bytesPerRow - length; j++) {
                sb.append("     ");
            }

            for (int j = 0; j < Math.min(length, bytesPerRow); j++) {
                if (row[j] >= 32 && row[j] <= 127) {
                    sb.append((char) row[j]);
                } else {
                    sb.append('.');
                }
            }

            if (i + bytesPerRow < bytes.length) {
                sb.append('\n');
                sb.append(' ');
                sb.append(' ');
            }
        }
        return sb.toString();
    }

    /**
     * Converts one byte to its hex representation with leading zeros. E.g. 255 -> FF, 12 -> 0C
     * 
     * @param b
     * @return
     */
    public static String toHexString(int b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }
}

Related

  1. toHexString(byte[] bytes)
  2. toHexString(byte[] bytes)
  3. toHexString(byte[] bytes)
  4. toHexString(byte[] bytes)
  5. toHexString(byte[] bytes)
  6. toHexString(byte[] bytes)
  7. toHexString(byte[] bytes)
  8. toHexString(byte[] bytes)
  9. toHexString(byte[] bytes)