create a hexidecimal string from a byte-array - Java java.lang

Java examples for java.lang:String Hex

Description

create a hexidecimal string from a byte-array

Demo Code


public class Main {
  public static void main(String[] argv) {
    byte[] byteArray = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
    System.out.println(stringFromBytes(byteArray));
  }//from   www . j a  v  a 2  s . c o m

  private static final short BYTE_SHIFT = 8;
  private static final short LOW_BYTE_MASK = (short) ((short) (1 << BYTE_SHIFT) - 1);
  private static final short HIGH_NIBBLE_MASK = (short) 0xf0;

  /**
   * Method stringFromBytes Description: create a hexidecimal string from a
   * byte-array
   * 
   * @param byteArray
   * @return String
   */

  public static String stringFromBytes(byte[] byteArray) {

    StringBuffer str = new StringBuffer("");

    for (int i = 0; i < byteArray.length; i++) {
      if ((int) (byteArray[i] & HIGH_NIBBLE_MASK) > 0) {
        str.append(Integer.toHexString((int) byteArray[i] & LOW_BYTE_MASK));
      } else {
        str.append("0" + Integer.toHexString((int) byteArray[i] & LOW_BYTE_MASK));
      }
    }

    return str.toString();
  }
}

Related Tutorials