Java 程序返回提供的字节数组的十六进制值
以下是提供的字节数组 −
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); // 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(); } }
结果
xyz Byte array to Hex String = 78797a
广告