Objective
Create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 rows in each screen. The program should pause after displaying each screen before displaying the next 24 rows.
In each row, the 16 bytes must be displayed first in hexadecimal format and then as characters. Bytes with ASCII code less than 32 must be displayed as a dot instead of the corresponding non-printable character.
You can look for "hex editor" on Google Images to see an example of the expected appearance.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces
using System;
using System.IO;
class HexDump
{
// Main method where the program execution begins
static void Main()
{
// File path (change this to the file you want to dump)
string filePath = "example.bin";
// Call the DumpFile method to display the content of the file
DumpFile(filePath);
}
// Method to dump the contents of the file in hexadecimal format
static void DumpFile(string filePath)
{
try
{
// Open the file in binary read mode
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Buffer to store bytes read from the file
byte[] buffer = new byte[16]; // 16 bytes per row
int rowNumber = 0;
int bytesRead;
// Loop to read the file 16 bytes at a time
while ((bytesRead = fs.Read(buffer, 0, 16)) > 0)
{
// Print hexadecimal representation of the bytes
PrintHexRow(buffer, bytesRead, rowNumber);
// Pause after every 24 rows
if (++rowNumber % 24 == 0)
{
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
}
catch (Exception ex)
{
// Catch any errors (like file not found) and display the error message
Console.WriteLine("Error: " + ex.Message);
}
}
// Method to print a single row of hexadecimal and ASCII characters
static void PrintHexRow(byte[] buffer, int bytesRead, int rowNumber)
{
// Print row number in hexadecimal format
Console.Write("{0:X8}: ", rowNumber * 16);
// Print the hexadecimal bytes
for (int i = 0; i < 16; i++)
{
if (i < bytesRead)
Console.Write("{0:X2} ", buffer[i]);
else
Console.Write(" "); // Print empty space for incomplete rows
}
// Print the ASCII representation of the bytes
Console.Write(" | ");
for (int i = 0; i < bytesRead; i++)
{
// If byte is printable, show it, else print '.'
char c = (char)buffer[i];
Console.Write(c >= 32 && c <= 126 ? c : '.');
}
// Move to the next line
Console.WriteLine();
}
}