java byte数组打印

十六位数组打印输出

  • 简单的方式
Byte[] bs = {0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F};
System.out.println(Arrays.toString(bs));
// 打印输出结果
[15, 31, 47, 63, 79, 95, 111]
  • 更加通用一点的方式
byte[] bs = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");
System.out.println(Arrays.toString(bs));

/**
 * 将String转换为byte[]
 * @param s String
 * @return byte[]
 */
public static byte[] hexStringToByteArray(String s) {
	int len = s.length();
	byte[] data = new byte[len / 2];
	for (int i = 0; i < len; i += 2) {
	data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
	}
	return data;
}
// 打印输出结果
[-32, 79, -48, 32, -22, 58, 105, 16, -94, -40, 8, 0, 43, 48, 48, -99]

普通数组打印输出

byte[] bs = "你好,这是一段字符串!".getBytes();
System.out.println(Arrays.toString(bs));
// 打印输出结果
[-28, -67, -96, -27, -91, -67, -17, -68, -116, -24, -65, -103, -26, -104, -81, -28, -72, -128, -26, -82, -75, -27, -83, -105, -25, -84, -90, -28, -72, -78, -17, -68, -127]

你可能感兴趣的:(java知识总结)