Syntax error Java Program to return the hexadecimal value of the supplied byte array

Java Program to return the hexadecimal value of the supplied byte array



The following is the supplied byte array −

byte[] b = new byte[]{'x', 'y', 'z'};

We have created a custom method “display” here and passed the byte array value. The same method converts byte array to hex string −

public static String display(byte[] b1){
   StringBuilder strBuilder = new StringBuilder();
   for(byte val : b1){
      strBuilder.append(String.format("%02x", val&0xff));
   }
   return strBuilder.toString();
}

Let us see the entire example now −

Example

 Live Demo

public class Demo {
   public static void main(String args[]) {
      byte[] b = new byte[]{'x', 'y', 'z'};
      /* byte array cannot be displayed as String because it may have non-printable
      characters e.g. 0 is NUL, 5 is ENQ in ASCII format */
      String str = new String(b);
      System.out.println(str);
      // byte array to Hex String
      System.out.println("Byte array to Hex String = " + display(b));
   }
   public static String display(byte[] b1){
      StringBuilder strBuilder = new StringBuilder();
      for(byte val : b1){
         strBuilder.append(String.format("%02x", val&0xff));
      }
      return strBuilder.toString();
   }
}

Output

xyz
Byte array to Hex String = 78797a
Updated on: 2019-07-30T22:30:24+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements