import java.io.*;
import java.nio.charset.StandardCharsets;
public class HelloWorld {
/**
* 生成类似 hexdump 的十六进制转储格式
* @param data 二进制数据
* @return 格式化后的字符串
*/
public static String hexDump(byte[] data) {
StringBuilder sb = new StringBuilder();
int offset = 0;
int length = data.length;
while (offset < length) {
// 1. 计算当前行处理的字节数(最多16字节)
int rowLength = Math.min(16, length - offset);
// 2. 格式化地址(例如: 00000000)
sb.append(String.format("%08X ", offset));
// 3. 生成十六进制部分
StringBuilder hex = new StringBuilder();
StringBuilder ascii = new StringBuilder();
for (int i = 0; i < rowLength; i++) {
int pos = offset + i;
byte b = data[pos];
// 十六进制部分(每字节两个字符)
hex.append(String.format("%02X ", b));
// ASCII 可打印字符(非打印字符显示为`.`)
char c = (char) (b & 0xFF);
if (Character.isISOControl(c) || (c > 0x7E)) {
ascii.append('.');
} else {
ascii.append(c);
}
// 在第八个字节后加空格分隔
if (i == 7) {
hex.append(" ");
}
}
// 4. 填充剩余空格(不足16字节的行)
if (rowLength < 16) {
int remaining = 16 - rowLength;
for (int i = 0; i < remaining; i++) {
hex.append(" "); // 每个未用字节用三个空格填充
}
if (rowLength < 8) {
hex.append(" ");
}
}
// 5. 拼接最终行
sb.append(hex)
.append(" ")
.append(ascii)
.append("\n");
offset += rowLength;
}
return sb.toString();
}
/**
* 从文件读取数据并生成 hexdump
*/
public static String hexDumpFile(String filePath) throws IOException {
try (InputStream is = new BufferedInputStream(new FileInputStream(filePath))) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(data)) != -1) {
buffer.write(data, 0, bytesRead);
}
return hexDump(buffer.toByteArray());
}
}
// 测试代码
public static void main(String[] args) {
try {
// 示例:转储字符串
String testData = "Hello, HexDump!\nThis is a test.";
byte[] bytes = testData.getBytes(StandardCharsets.UTF_8);
System.out.println(hexDump(bytes));
// 示例:转储文件
System.out.println(hexDumpFile("test.bin"));
} catch (IOException e) {
e.printStackTrace();
}
mainx();
}
public static void mainx() {
System.out.println("Hello, World!");
byte[] selfCheckType = new byte[3];
selfCheckType[0] = (byte)0x85; //0X85
selfCheckType[1] = (byte)1;
selfCheckType[2] = (byte)0x83; //0X83
System.out.println(hexDump(selfCheckType));
}
}
javac -encoding UTF-8 .\HelloWorld.java
java HelloWorld