进制之间的任意转换

Posted 猿来到此

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了进制之间的任意转换相关的知识,希望对你有一定的参考价值。

进制之间的任意转换

一、10进制数转换任意进制的数

基本思路:求余数,直到被除数/进制=0,然后按逆序排列。

    C#:

static void TestMath_5(int number, int scale)//number除数,scale进制

{

int mynumber=number ;

string mystr = null;

char[] mychar=new char[100];

int j = 0;

while (number >= scale)

{

if (number % scale < 10) { mychar[j++] = (char)(number % scale + ‘0‘); }

else { mychar[j++] = (char)(number % scale -10+ ‘A‘); }

number = number / scale;

}

if (number < scale)

{

if (number < 10) { mychar[j] = (char)(number % scale + ‘0‘); }

else { mychar[j] = (char)(number % scale -10+ ‘A‘); }

}

for (int i = 0; i <=j; i++)

{

mystr += mychar[j - i ];

}

Console.WriteLine("{0}={1}", mynumber, mystr);

}

    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)

    End Sub

二、任意进制的数转换10进制数

基本思路:对对应加权位上的数*对应的加权值,然后全部加起来。

     C#:

       static void TestMath_6(string number,int scale)

{

int length = number.Length;

int num =0;

int gt=0 ;

for (int i = 0; i <length; i++)

{

if (number[i] >= ‘a‘) { gt = number[i] - ‘a‘+10; }

else if (number[i] >= ‘A‘) { gt = number[i] - ‘A‘+10; }//每个位置的数

else if (number[i] >= ‘0‘) { gt = number[i]-‘0‘; }

num += gt * (int)(Math.Pow(scale, (length-i-1)));

}

Console.WriteLine("{0}={1}", number, num);

}

    VB.NET:

Sub TestMath_6(number As String, scale As Integer)

Dim num As Integer = 0 返回的数

Dim gt As Integer = 0 每个加权位上的值

Dim length As Integer = number.Length

For i = 0 To length - 1

If (number(i) >= "a") Then

gt = CInt(AscW(number(i))) - AscW("a") + 10

ElseIf (number(i) >= "A") Then

gt = CInt(AscW(number(i))) - AscW("A") + 10

ElseIf (number(i) >= "0") Then

gt = CInt(AscW(number(i))) - 48

End If

num += gt * (CInt(scale ^ (length - i - 1)))

Next

Console.WriteLine("{0}={1}", number, num)

End Sub

以上是关于进制之间的任意转换的主要内容,如果未能解决你的问题,请参考以下文章

组成原理中关于小数和整数关于十,二,十六,八进制之间任意的转换

POJ44:正整数的任意进制转换

任意进制转换算法

任意进制转换算法

进制间的相互转换

任意进制间转换