Bytes to characters and vice versa

- 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);
}

Full source code listing:

download sourcecode