Numerical encoding of text using c-sharp

- Posted in Coding by

It just so happens that any character we might use in a string has a numerical encoding. The alphabet ranges from 65-90 for capital letters A through Z, and from 97-122 for lowercase letters a-z. When we want to work with text encoding, we need to add the following namespace to the top of our source code file:

using System.Text;

The numerical representation of our English alphabet takes the form of unique numbers for each upper and lowercase letter, and these are stored in a variable type called byte. A byte is an 8-bit integer that can hold values from 0 to 255.

If we have a string variable named sChar, we can obtain its numerical encoding as follows, if we have referenced the System.Text namespace:

byte[] bt = Encoding.Default.GetBytes(sChar);

The reverse is encoding bytes to characters. If we have an array of bytes, we can convert each element’s value to its corresponding character:

byte[] bytes = {40, 80, 20};
char result;
foreach(byte number in bytes)
{
    result = Convert.ToChar(number);
    Console.WriteLine(“{0} converts to {1}.”, number, result);
}

You can download a sample program here.

Handy way to access constants in c-sharp application

- Posted in Coding by

It can be convenient to put constants that need to be available throughout your project into their own public class, accessible from other code belonging to the same namespace. For instance, if our project namespace is EarthApotheosis, we might set up our constants like this:

using System;

namespace EarthApotheosis {

  public class EarthApotheosisConstants
  {
      public static string TITLE = Properties.Resources.Title;
      public const int KILLS_TO_EARN_ONE_COMBAT_ADV_POINT = 50;
      public const int MAX_CHARS_PER_LINE_IN_LABEL_DISPLAY = 80;
      public const string INPUT_CURRENTLY_DISABLED = "Input currently disabled...";
      public const string AVATAR_NAME_NEEDED = "Please specify avatar name...";

  }

}

We'd then reference constants from with our project's main form as follows:

int max_chars = EarthApotheosisConstants.MAX_CHARS_PER_LINE_IN_LABEL_DISPLAY;