- 进制之间的任意转换
一、10进制数转换任意进制的数
基本思路:求余数,直到被除数/进制=0,然后按逆序排列。
C#:
1 static void TestMath_6(string number, int scale) 2 { 3 int length = number.Length; 4 int num = 0; 5 int gt = 0; 6 for (int i = 0; i < length; i++) 7 { 8 if (number[i] >= 'a') 9 { 10 gt = number[i] - 'a' + 10; 11 } 12 else if (number[i] >= 'A') 13 { 14 gt = number[i] - 'A' + 10; 15 }//每个位置的数 16 else if (number[i] >= '0') 17 { 18 gt = number[i] - '0'; 19 20 } 21 num += gt * (int)(Math.Pow(scale, (length - i - 1))); 22 } 23 Console.WriteLine("{0}={1}", number, num); 24 25 }
1 //优化代码 2 static void TestMath_5(int number, int scale)//number除数,scale进制 3 { 4 int mynumber = number; 5 string mystr = null; 6 char[] mychar = new char[100]; 7 int j = 0; 8 do 9 { 10 if (number % scale < 10) { mychar[j++] = (char)(number % scale + '0'); } 11 else { mychar[j++] = (char)(number % scale - 10 + 'A'); } 12 number = number / scale; 13 } while (number / scale!=0); 14 for (int i = 1; i <= j; i++) 15 { 16 mystr += mychar[j - i]; 17 } 18 Console.WriteLine("{0}={1}", mynumber, mystr); 19 }
VB.NET:
Sub TestMath_5(number As Integer, scale As Integer) Dim mynumber As Integer = number Dim mystr As String = Nothing Dim mychar(100) As Char Dim i, j As Integer While (number >= scale) If (number Mod scale < 10) Then mychar(i) = ChrW(number Mod scale + AscW("0")) Else mychar(i) = ChrW(number Mod scale - 10 + AscW("A")) End If i += 1 number = Math.Truncate(number / scale) End While If (number < scale) Then If (number Mod scale < 10) Then mychar(i) = ChrW(number Mod scale + AscW("0")) Else mychar(i) = ChrW(number Mod scale - 10 + AscW("A")) End If End If For j = 0 To i mystr += mychar(i - j) Next Console.WriteLine("{0}={1}", mynumber, mystr)
二、任意进制的数转换10进制数
基本思路:对对应加权位上的数*对应的加权值,然后全部加起来。
C#:
1 static void TestMath_6(string number, int scale) 2 { 3 int length = number.Length; 4 int num = 0; 5 int gt = 0; 6 for (int i = 0; i < length; i++) 7 { 8 if (number[i] >= 'a') 9 { 10 gt = number[i] - 'a' + 10; 11 } 12 else if (number[i] >= 'A') 13 { 14 gt = number[i] - 'A' + 10; 15 } 16 17 //每个位置的数 18 else if (number[i] >= '0') 19 { 20 gt = number[i] - '0'; 21 } 22 num += gt * (int)(Math.Pow(scale, (length - i - 1))); 23 } 24 Console.WriteLine("{0}={1}", number, num); 25 26 }
VB.NET:
1 Sub TestMath_6(number As String, scale As Integer) 2 3 Dim num As Integer = 0 '返回的数 4 Dim gt As Integer = 0 '每个加权位上的值 5 Dim length As Integer = number.Length 6 For i = 0 To length - 1 7 If (number(i) >= "a") Then 8 gt = CInt(AscW(number(i))) - AscW("a") + 10 9 ElseIf (number(i) >= "A") Then 10 gt = CInt(AscW(number(i))) - AscW("A") + 10 11 ElseIf (number(i) >= "0") Then 12 gt = CInt(AscW(number(i))) - 48 13 End If 14 15 num += gt * (CInt(scale ^ (length - i - 1))) 16 Next 17 Console.WriteLine("{0}={1}", number, num) 18 End Sub