ASCII码转字符串

来源:互联网 发布:淘宝情趣内衣买家秀吧 编辑:程序博客网 时间:2024/05/20 14:27
public static int Asc(string character)  {   if (character.Length == 1)   {    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();    int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];    return (intAsciiCode);   }   else   {    throw new Exception("Character is not valid.");   }  }ASCII码转字符: 单个字符public static string Chr(int asciiCode)  {   if (asciiCode >= 0 && asciiCode <= 255)   {    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();    byte[] byteArray = new byte[] { (byte)asciiCode };    string strCharacter = asciiEncoding.GetString(byteArray);    return (strCharacter);   }   else   {    throw new Exception("ASCII Code is not valid.");   }  } Excel专用/// <summary>        /// ASCII码转字符串(转换为Excel列的形式:A/B/C...AA/AB/AC...BA/BB/......)        /// </summary>        /// <param name="asciiCode">最大数字255(即Excel最末列IV)</param>        /// <returns></returns>        public static string Chr(int asciiCode)        {            if (asciiCode > 0 && asciiCode <= 255)            {                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();                string strCharacter = string.Empty;                byte[] byteArray = null;                int division = (asciiCode - 64) / 26;                int mod = (asciiCode - 64) % 26;                if (mod == 0)                {                    division = division - 1;                    mod = 26;                }                if ((division == 0) && (mod <= 26))                {                    byteArray = new byte[] { (byte)(mod + 64) };                    strCharacter = strCharacter + asciiEncoding.GetString(byteArray);                }                else                {                    byteArray = new byte[] { (byte)(division + 64) };                    strCharacter = strCharacter + asciiEncoding.GetString(byteArray);                    byteArray = new byte[] { (byte)(mod + 64) };                    strCharacter = strCharacter + asciiEncoding.GetString(byteArray);                }                return strCharacter;            }            else            {                return "ASCII Code is not valid.";            }        }

0 0
原创粉丝点击