C# 字符转ASCII码,ASCII码转字符

字符转ASCLL:

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.";
            }
        }
  转自:
http://blog.csdn.net/maozhu_yimi/article/details/6091883

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值