English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Here is our byte array.
byte[] b = new byte[]{'p', 'q', 'r'};
We have created a custom method "display" here and passed the byte array value. The same method converts the byte array to a hexadecimal 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(); }
Now let's look at the entire example.
public class Demo { public static void main(String args[]) { byte[] b = new byte[]{'p', 'q', 'r'}; /* 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); //Hexadecimal string byte array 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 Result
pqr Byte array to Hex String = 707172