以下是提供的字节数组-
byte[] b = new byte[]{'x', 'y', 'z'};
我们在此处创建了一个自定义方法“ display”,并传递了字节数组值。相同的方法将字节数组转换为十六进制字符串-
public static String display(byte[] b1){ StringBuilder strBuilder = new StringBuilder(); for(byte val : b1){ strBuilder.append(String.format("%02x", val&0xff)); } return strBuilder.toString(); }
现在让我们来看整个示例-
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); //十六进制字符串的字节数组 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(); } }
输出结果
xyz Byte array to Hex String = 78797a