45 lines
1.4 KiB
Java
Raw Permalink Normal View History

2017-01-20 21:30:44 -08:00
// strings/Hex.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-07-28 12:48:23 -06:00
// {java onjava.Hex}
package onjava;
2015-06-15 17:47:35 -07:00
import java.io.*;
import java.nio.file.*;
2015-06-15 17:47:35 -07:00
public class Hex {
public static String format(byte[] data) {
StringBuilder result = new StringBuilder();
int n = 0;
for(byte b : data) {
if(n % 16 == 0)
result.append(String.format("%05X: ", n));
result.append(String.format("%02X ", b));
n++;
if(n % 16 == 0) result.append("\n");
}
result.append("\n");
return result.toString();
}
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2015-06-15 17:47:35 -07:00
if(args.length == 0)
// Test by displaying this class file:
System.out.println(format(
2016-07-07 14:58:56 -06:00
Files.readAllBytes(Paths.get(
"build/classes/java/main/onjava/Hex.class"))));
2015-06-15 17:47:35 -07:00
else
System.out.println(format(
Files.readAllBytes(Paths.get(args[0]))));
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output: (First 6 Lines)
2016-07-22 14:45:35 -06:00
00000: CA FE BA BE 00 00 00 34 00 61 0A 00 05 00 31 07
00010: 00 32 0A 00 02 00 31 08 00 33 07 00 34 0A 00 35
00020: 00 36 0A 00 0F 00 37 0A 00 02 00 38 08 00 39 0A
00030: 00 3A 00 3B 08 00 3C 0A 00 02 00 3D 09 00 3E 00
00040: 3F 08 00 40 07 00 41 0A 00 42 00 43 0A 00 44 00
00050: 45 0A 00 14 00 46 0A 00 47 00 48 07 00 49 01 00
2015-06-15 17:47:35 -07:00
...
2015-09-07 11:44:36 -06:00
*/