搞懂一直模糊不清的進制轉換 & C#代碼實現轉換

什麼是進制轉換?

進制轉換:

進制轉換是人們利用符號來計數的方法。進制轉換由一組數碼符號和兩個基本因素“基數”與“位權”構成。
基數是指,進位計數制中所採用的數碼(數制中用來表示“量”的符號)的個數。
位權是指,進位制中每一固定位置對應的單位值。

二進制,八進制,十六進制與十進制數之間的關係

二進制 (B:binary) 八進制 (O:octal) 十進制(D:decimal) 十六進制(H:hexadeclmal)
0 0 0 0
1 1 1 1
10 2 2 2
11 3 3 3
100 4 4 4
101 5 5 5
110 6 6 6
111 7 7 7
1000 8 10 8
1001 9 11 9
1010 10 12 A
1011 11 13 B
1100 12 14 C
1101 13 15 D
1110 14 16 E
1111 15 17 F

任何進制轉換爲10進制:
將任意進制數 - 按位權展開的多項式,各位數碼乘以各自的權值且累加起來,就得到該r進制數對應的十進制數。
例子如下圖:

111


二、八、十六進制數相互轉換
二進制、八進制、十六進制之間存在特殊關係:81=23、161=24,即1位八進制數相當於3位二進制數,1位十六進制數相當於4位二進制數。
根據上述關係,可以得到它們之間的轉換方法:
1.二進制數轉換成八進制數時,以小數點爲中心向左右兩邊分組,每3位爲一組轉換成相應的八進制數,兩頭不足3位用0補;
2.二進制數轉換成十六進制數時,以小數點爲中心向左右兩邊分組,每4位爲一組轉換成相應的十六進制數,兩頭不足4位用0補;
3.八進制數轉換成十六進制數或十六進制數轉換成八進制數時,可以藉助二進制。

例子:

在這裏插入圖片描述


C#代碼進行各進制的轉換
     	public static void JinZhiZhuangHuan()
        {
            #region 十進制
            Console.WriteLine("十進制 10 轉換爲其他進制:");
            int number = 10;

            //十進制轉二進制字符串
            Console.WriteLine(Convert.ToString(number, 2));

            //十進制轉八進制字符串
            Console.WriteLine(Convert.ToString(number, 8));

            //十進制轉十六進制字符串
            Console.WriteLine(Convert.ToString(number, 16));
            #endregion
            Console.WriteLine();

            #region 二進制
            Console.WriteLine("二進制 1010 轉換爲其他進制:");
            string binary = "1010";

            //轉八進制數
            Console.WriteLine(Convert.ToString(Convert.ToInt32(binary, 2), 8));

            //轉十進制數
            Console.WriteLine(Convert.ToInt32(binary, 2));

            //轉十六進制數
            Console.WriteLine(string.Format("{0:x}", Convert.ToInt32(binary, 2)));

            #endregion
            Console.WriteLine();

            #region 八進制
            Console.WriteLine("八進制 12 轉換爲其他進制:");
            string octal = "12";
            //轉二進制數
            Console.WriteLine(Convert.ToString(Convert.ToInt32(octal, 8), 2));

            //轉十進制數
            Console.WriteLine(Convert.ToInt32(octal, 8).ToString());

            //轉十六進制數
            Console.WriteLine(Convert.ToString(Convert.ToInt32(octal, 8), 16));

            #endregion
            Console.WriteLine();

            #region 十六進制
            Console.WriteLine("十六進制 0xA 轉換爲其他進制:");
            //十六進制轉二進制字符串
            Console.WriteLine(Convert.ToString(0xA, 2));

            //十六進制轉十進制數
            Console.WriteLine(Convert.ToString(0xA, 8));

            //十六進制轉十進制數
            Console.WriteLine(Convert.ToString(0xA, 10));

            #endregion
        }

結果


進制轉換在線工具:
https://tool.oschina.net/hexconvert
https://www.sojson.com/hexconvert.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章