C# 十進位和十六進位轉換

來源:互聯網
上載者:User

在C#中,十進位和十六進位轉換非常簡單,方法如下:

十進位轉為十六進位:

1 int a = 100;2 String strA = a.ToString("x8");

十六進位轉為十進位:

1 int b= Int32.Parse("266", System.Globalization.NumberStyles.HexNumber);

 也可以使用下述方法:

 1         /// <summary> 2         /// 十六進位換算為十進位 3         /// </summary> 4         /// <param name="strColorValue"></param> 5         /// <returns></returns> 6         public static int GetHexadecimalValue(String strColorValue) 7         { 8             char[] nums = strColorValue.ToCharArray(); 9             int total = 0;10             try11             {12                 for (int i = 0; i < nums.Length; i++)13                 {14                     String strNum = nums[i].ToString().ToUpper();15                     switch (strNum)16                     {17                         case "A":18                             strNum = "10";19                             break;20                         case "B":21                             strNum = "11";22                             break;23                         case "C":24                             strNum = "12";25                             break;26                         case "D":27                             strNum = "13";28                             break;29                         case "E":30                             strNum = "14";31                             break;32                         case "F":33                             strNum = "15";34                             break;35                         default:36                             break;37                     }38                     double power = Math.Pow(16, Convert.ToDouble(nums.Length - i - 1));39                     total += Convert.ToInt32(strNum) * Convert.ToInt32(power);40                 }41 42             }43             catch (System.Exception ex)44             {45                 String strErorr = ex.ToString();46                 return 0;47             }48 49 50             return total;51         }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.