文字のASCIIコードを取得するには文字をint型にキャストすることで実現できます。
逆に、ASCIIコードから対応する文字を取得するにはコードをchar型にキャストすることで実現できます。
Visual BasicのAsc関数、Chr関数の名前にならって次のようなプログラムを作成してみます。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class MyAsciiEncoding
{
public static int Asc(char character)
{
return (int)character;
}
public static char Chr(uint charCode)
{
if(charCode < 256)
{
return (char)charCode;
}
else
{
throw new ArgumentOutOfRangeException("charCode",
"The argument must be between 0 and 255.");
}
}
}
class Program
{
static void Main()
{
try
{
Console.WriteLine("Asc('D')={0}", MyAsciiEncoding.Asc('D'));
Console.WriteLine("Asc('g')={0}", MyAsciiEncoding.Asc('g'));
Console.WriteLine("Chr(68)='{0}'", MyAsciiEncoding.Chr(68));
Console.WriteLine("Chr(103)='{0}'", MyAsciiEncoding.Chr(103));
Console.WriteLine("Chr(500)='{0}'", MyAsciiEncoding.Chr(500));
}
catch(ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
}
}
}
上のプログラムを実行すると以下のような結果となります。
Asc('D')=68
Asc('g')=103
Chr(68)='D'
Chr(103)='g'
The argument must be between 0 and 255.
パラメータ名: charCode