Java 中将字节数组转换为十六进制字符串
以下是我们的字节数组。
byte[] b = new byte[]{'p', 'q', 'r'};
我们在这里创建了一个自定义方法“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[]{'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); // 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(); } }
输出
pqr Byte array to Hex String = 707172
广告