Java byte array convert to hexadecimal String with bitwise operator

Description

Java byte array convert to hexadecimal String with bitwise operator

public class Main {

   public static void main(String[] argv) {
      byte[] b = "demo2s.com".getBytes();
      String hex = byteArrayToHexString(b);
      System.out.println(hex);/*  ww  w .  j a  va 2s .co m*/

      b =  hexStringToByte(hex);

      System.out.println(new String(b));
   }

   /**
    * Converts a byte array into a hexadecimal string
    *
    *
    * @param b byte array
    *
    * @return hex string
    */
   public static String byteArrayToHexString(byte[] b) {

      int len = b.length;
      char[] s = new char[len * 2];

      for (int i = 0, j = 0; i < len; i++) {
         int c = ((int) b[i]) & 0xff;

         s[j++] = (char) HEXBYTES[c >> 4 & 0xf];
         s[j++] = (char) HEXBYTES[c & 0xf];
      }

      return new String(s);
   }
   /**
    * Given a hexstring this will return the byte array corresponding to the
    * string
    * @param hex the hex String array
    * @return a byte array that is a hex string representation of the given
    *         string. The size of the byte array is therefore hex.length/2
    */
   public static byte[] hexStringToByte(String hex) {
     byte[] bts = new byte[hex.length() / 2];
     for (int i = 0; i < bts.length; i++) {
       bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
     }
     return bts;
   }
   private static final byte[] HEXBYTES = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',
         (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
         (byte) 'f' };

}



PreviousNext

Related