Creating an ASCII Table with C#
After watching The Martian for the somethingth time I was thinking about the scene where Mark Watney needs an ASCII table and hexadecimal to help him communicate with NASA. The character searches through the belongings of the crew to find the table, but what if he couldn’t find one?
Surely it would be easy to create an ASCII table with a simple program.
There are times when I want to program for the sheer joy of it. This is one of those times.
Single column table
Here is how to create an ASCII table in decimal and hexadecimal.
for (int i = 0; i < 127; i++)
{
Console.WriteLine($"{(char) i} {i.ToString().PadLeft(3)} {i.ToString("X")}");
}
This prints a simple single column table.
Multi-column table
Of course, for a little more fun, I wanted to print this out in nice columns.
for (int i = 0; i <= 31; i++)
{
string col1;
if (i is >= 7 and <= 13)
{
col1 = $" {i.ToString().PadLeft(3)} {i.ToString("X")}"; // chars between 7 and 13 mess with the alignment
}
else
{
col1 = $"{(char)(i)} {(i).ToString().PadLeft(3)} {(i).ToString("X")}";
}
string col2 = $"{(char)(i+32)} {(i+32).ToString().PadLeft(3)} {(i+32).ToString("X")}";
string col3 = $"{(char)(i+64)} {(i+64).ToString().PadLeft(3)} {(i+64).ToString("X")}";
string col4 = $"{(char)(i+96)} {(i+96).ToString().PadLeft(3)} {(i+96).ToString("X")}";
Console.WriteLine($"{col1} \t {col2} \t {col3} \t {col4}");
}
A few other ways to get the ASCII table as hex
Create a file with the alphabet and any other characters you need.
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
In Windows there is a command called hex-format
. Pass the alphabet file to it.
format-hex alphabet.txt
In Linux there are a few ways to do this.
xxd alphabet.txt
od -x alphabet.txt
hexdump -v -e '/1 "%02X "' alphabet.txt