C# ASCII Transformation, Convert Char to Index

This C# example page uses transformations on ASCII values to convert digit chars to ints and to lowercase letters.
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
C# program that converts ASCII digits 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}"); } } } Output 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.

So: We can add 32 to go from uppercase to lower. This might seem the opposite of what is logical.

C# program that lowercases chars in ASCII 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}"); } } } Output 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.

C# program that converts letters to indexes 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}"); } } } Output 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.ASCII TableTree
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls