Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Hexdump.cs
- * A simple command-line Hex dumper
- *
- * Copyright (c) 2016 Rubyist
- * This work is free. You can redistribute it and/or modify it under the
- * terms of the Do What The Fuck You Want To Public License, Version 2,
- * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
- */
- using System;
- using System.IO;
- public class Hexdump
- {
- public static void Main(String[] args)
- {
- /* Print usage information */
- if (args.Length != 1)
- {
- Usage();
- }
- if (args[0] == "--help" || args[0] == "-h")
- {
- Usage();
- }
- /* Open and dump file */
- try
- {
- FileStream file = File.Open(args[0], FileMode.Open);
- DumpFile(file);
- file.Close();
- }
- catch (Exception)
- {
- Console.WriteLine("Could not open file");
- Environment.Exit(-1);
- }
- }
- static void PrintAscii(byte[] buffer, int len)
- {
- /* Print excess spaces for last line of a hex dump */
- if (len < 16)
- {
- int spaces = (((16 - len) * 5) / 2) + (len % 2);
- for (int i = 0; i < spaces; i++)
- {
- Console.Write(' ');
- }
- }
- /* Print ascii values of all non-whitespace 7-bit ascii chars */
- for (int i = 0; i < len; i++)
- {
- if (buffer[i] < 32 || buffer[i] > 126)
- {
- Console.Write('.');
- }
- else
- {
- Console.Write(Convert.ToChar(buffer[i]));
- }
- }
- }
- static void Usage()
- {
- Console.WriteLine("usage: Hexdump binfile");
- Environment.Exit(0);
- }
- static void DumpFile(FileStream file)
- {
- /* Write header */
- Console.WriteLine(
- "Offset: " +
- "Bytes: " +
- "ASCII:"
- );
- /* Write the following information:
- * Offset: 64 bit value represented in hex.
- * Bytes: 8 groups of 2 bytes each, represented as 4 hex digits.
- * ASCII: 7-bit ascii interpretation of data. Whitespace are '.'
- */
- byte[] buffer = new byte[16];
- while (file.Position != file.Length)
- {
- Console.Write("0x{0}: ", file.Position.ToString("X16"));
- int written = file.Read(buffer, 0, 16);
- for (int i = 0; i < written; i++)
- {
- Console.Write(buffer[i].ToString("X2"));
- if (i%2 == 1)
- {
- Console.Write(' ');
- }
- }
- PrintAscii(buffer, written);
- Console.WriteLine("");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement