Skip to content

Instantly share code, notes, and snippets.

@mikedugan
Created January 4, 2014 00:41
Show Gist options
  • Save mikedugan/8249762 to your computer and use it in GitHub Desktop.
Save mikedugan/8249762 to your computer and use it in GitHub Desktop.
the atbash cipher replaces each character in a string with its inverse - a becomes z, b becomes y, etc
class AtbashTable
{
/// <summary>
/// Lookup table to shift characters.
/// </summary>
char[] _shift = new char[char.MaxValue];
/// <summary>
/// Generates the lookup table.
/// </summary>
public AtbashTable()
{
// Set these as the same.
for (int i = 0; i < char.MaxValue; i++)
{
_shift[i] = (char)i;
}
// Reverse order of capital letters.
for (char c = 'A'; c <= 'Z'; c++)
{
_shift[(int)c] = (char)('Z' + 'A' - c);
}
// Reverse order of lowercase letters.
for (char c = 'a'; c <= 'z'; c++)
{
_shift[(int)c] = (char)('z' + 'a' - c);
}
}
/// <summary>
/// Apply the Atbash cipher.
/// </summary>
public string Transform(string value)
{
try
{
// Convert to char array
char[] a = value.ToCharArray();
// Shift each letter.
for (int i = 0; i < a.Length; i++)
{
int t = (int)a[i];
a[i] = _shift[t];
}
// Return new string.
return new string(a);
}
catch
{
// Just return original value on failure.
return value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment