1 static void Main(string[] args)
2 {
3 if (args.Length != 1)
4 {
5 Console.Error.WriteLine("usage: hexdmper file-to-dump");
6 System.Environment.Exit(1);
7 }
8 if (!File.Exists(args[0]))
9 {
10 Console.Error.WriteLine("File does not exist: {0}", args[0]);
11 System.Environment.Exit(2);
12 }
13 using (Stream input = File.OpenRead(args[0]))
14 {
15 //------记录当前所在字节的位置
16 int position = 0;
17 //------缓冲区字节数组,每次处理最多16个字节
18 byte[] buffer = new byte[16];
19 //------循环直至流结束位置
20 while (position < input.Length)
21 {
22 //------填充buffer数组,并得到读取的字节数量,可能为0(当文件字节数量正好是16的整数倍)
23 int byteRead = input.Read(buffer, 0, buffer.Length);
24 if (byteRead > 0)
25 {
26 //------首先写4位16进制的偏移量,后面加个空格
27 Console.Write("{0}: ", String.Format("{0:x4}", position));
28 //------更新当前位置
29 position += byteRead;
30 //------遍历16个字节的缓冲区的每一位
31 for (int i = 0; i < 16; i++)
32 {
33 //------再写16进制数据,就是刚读的16个字节的数据,有可以小于16字节,所以先判断
34 if (i < byteRead)
35 {
36 //------以2位16进制输出字节,后面加个空格
37 string hex = String.Format("{0:x2}", buffer[i]);
38 Console.Write(hex + " ");
39
40 //------不能显示的非打印字符此时可用小点替换,此处250改成了127,因为大于127控制台也显示为?号
41 if (buffer[i] < 32 || buffer[i] > 127) { buffer[i] = (byte)'.'; }
42 }
43 else
44 //------缓冲区“空白”部分输出空格补齐排版
45 Console.Write(" ");
46 //------每循环到中位置加短横线作个分界
47 if (i == 7)
48 Console.Write("-- ");
49 }
50 //------取有效的字节转换成字符串
51 buffer = buffer.Take<byte>(byteRead).ToArray<byte>();
52 //------根据编码取得更新后的缓冲区内的字符串
53 string bufferContents = Encoding.UTF8.GetString(buffer);
54 //------输出整个字符串
55 Console.WriteLine(" " + bufferContents);
56 }
57 }
58 }
59 //Console.ReadKey();
60 }