ASCII TransformationUse transformations on ASCII values to convert digit chars to ints and to lowercase letters.
C#
ASCII transformations. In ASCII we find each letter, digit, whitespace and symbol character has an underlying int. The lowercase "a" is 97. The digit "1" is 49.
By adding or subtracting, we can transform one ASCII character into another. This enables great optimizations. We can apply many of these optimizations in certain programs.
First example. The character "1" is equal to the value 49. It is the second digit, and the "0" is 48. We can exploit this in a C# program by subtracting 48 to go from char to int.
And We can parse a string containing digits and immediately use math on these values. This can speed up some programs.
Parse
using System; class Program { static void Main() { // Convert char values to equivalent ints. string values = "1234"; for (int i = 0; i < values.Length; i++) { int convertedDigit = values[i] - 48; Console.WriteLine(\$"Char: {values[i]}; Digit: {convertedDigit}"); } } }
Char: 1; Digit: 1 Char: 2; Digit: 2 Char: 3; Digit: 3 Char: 4; Digit: 4
Lowercase. In ASCII we find that lowercase letters are stored after uppercase letters. Lowercase letters are near the end of the ASCII table.
Detail We can add 32 to go from uppercase to lower. This might seem the opposite of what is logical.
using System; class Program { static void Main() { // Convert uppercase values to lowercase. string values = "ABCD"; for (int i = 0; i < values.Length; i++) { char convertedChar = (char)(values[i] + 32); Console.WriteLine(\$"Uppercase: {values[i]}; Lowercase: {convertedChar}"); } } }
Uppercase: A; Lowercase: a Uppercase: B; Lowercase: b Uppercase: C; Lowercase: c Uppercase: D; Lowercase: d
Letter indexes. Suppose you have a trie and want to store 26 child nodes on it. We can convert lowercase letters to the range 0-25 and then index an array.
Here We subtract 97 to go from a letter to an index. The lowercase letter "b" for example is now the value 1.
using System; class Program { static void Main() { // Convert lowercase letters to indexes. string values = "abcd"; for (int i = 0; i < values.Length; i++) { int convertedIndex = values[i] - 97; Console.WriteLine(\$"Letter: {values[i]}; Index: {convertedIndex}"); } } }
Letter: a; Index: 0 Letter: b; Index: 1 Letter: c; Index: 2 Letter: d; Index: 3
A summary. For ASCII, these transformations are reliable. They are fast, and can be used in many applications like search utilities to speed up queries.
Tree
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.