Java byte array convert to String for debug

Description

Java byte array convert to String for debug

public class Main {
  public static void main(String[] argv) {
    byte[] b = "demo2s.com".getBytes();
    /* w ww. ja  v a2  s .c om*/
    String s = toString(b);
    System.out.println(s);
  }
  /**
   * Print a byte array as a String
   */
  public static String toString(byte[] bytes) {

      StringBuilder sb = new StringBuilder(4 * bytes.length);
      sb.append("[");

      for (int i = 0; i < bytes.length; i++) {
          sb.append(unsignedByteToInt(bytes[i]));
          if (i + 1 < bytes.length) {
              sb.append(",");
          }
      }

      sb.append("]");
      return sb.toString();
  }

  /**
   * Convert an unsigned byte to an int
   */
  public static int unsignedByteToInt(byte b) {
      return (int) b & 0xFF;
  }
}



PreviousNext

Related