C#十进制与十六进制转换

C#中关于十进制,十六进制的转换,可以用以下几种方法

(1)

string BID="16";//十六进制数

int a=Convert.ToInt32(BID, 16);//将“16”当成是一个十六进制数,现将其转成十进制数,此时a的值为22

(2)

 int dddddd = 16;//任意数
  string dddddddd = Convert.ToString(dddddd, 16);//“16”当成是一个十进制数,现将其转成十六进制数,此时值为“10”

或者

 int dddddd = 0x16;
                string dddddddd = Convert.ToString(dddddd, 10);//此时值为“22”

(3)

自己写方法实现

 

  public int HexToDec(string strHex)
        {
            int iRet = 0;
            char[] strArray;
            int i = 0;
            strHex = strHex.Trim();
            strHex = strHex.ToUpper();
            strArray = strHex.ToCharArray();
            i = strArray.Length;
            if (i <= 0)
                return -1;

            if (strArray[i - 1] != 'H')
            {
                try
                {
                    iRet = Convert.ToInt32(strHex);
                }
                catch (FrameException ex)
                {
                    throw ex;
                }
                catch (Exception e)
                {
                    throw new FrameException("16进制转为10进制", "2", e.Message, DateTime.Now);
                }
            }
            else
            {
                for (int j = 0; j < i - 1; j++)
                {
                    if (strArray[j] >= '0' && strArray[j] <= '9')
                    {
                        iRet = iRet * 16 + strArray[j] - '0';
                    }
                    else if (strArray[j] >= 'A' && strArray[j] <= 'F')
                    {
                        iRet = iRet * 16 + strArray[j] - 'A' + 10;
                    }
                    else
                    {
                        throw new FrameException("16进制转为10进制", "2", "输入数据非法", DateTime.Now);
                    }

                }
            }
            return iRet;

posted @ 2011-01-05 16:43  orchids  阅读(7501)  评论(3编辑  收藏  举报