1、进制的计算,要换算的数字N,进制D(不超过十六进制)。
步骤一:N除以D,商为Q,余数为R,
根据ASCII表,R如果小于10,那么直接加上48,然后转为Char类型,对应0-9;R如果大于等于10,那么减去10,加上65,(或者直接加上55),然后转为Char类型,对应A-F。转换后的字符存入栈(Push);
步骤二:N=Q,继续执行步骤一,直到商为0
步骤三:由于栈是先进后出,按照此原理,取出栈内的字符(Pop),就可以组成转换后的字符串。
Code3-1
Stack.vb:
Public Class Stack
Private stackarray() As Object
Private Const defaultCapacity = 10
Private size As Integer
Public ReadOnly Property Count As Integer
Get
Return size
End Get
End Property
Sub New()
stackarray = New Object(defaultCapacity - 1) {}
size = 0
End Sub
Sub New(ByVal initialCapacity As Integer)
If initialCapacity < 0 Then
Throw New ArgumentOutOfRangeException("栈空间不能小于零!")
End If
If initialCapacity < defaultCapacity Then
initialCapacity = defaultCapacity
End If
stackarray = New Object(initialCapacity - 1) {}
size = 0
End Sub
Public Function Pop() As Object
If size = 0 Then
Throw New InvalidOperationException("栈下溢,栈内已无数据!")
End If
Dim obj2 As Object
size = size - 1
obj2 = stackarray(size)
stackarray(size) = Nothing
Return obj2
End Function
Public Sub Push(ByVal obj As Object)
If size = stackarray.Length Then
Dim destinationArray() As Object = New Object(stackarray.Length * 2) {}
Array.Copy(stackarray, 0, destinationArray, 0, stackarray.Length)
stackarray = destinationArray
End If
stackarray(size) = obj
size += 1
End Sub
End Class
Module1.vb:
Module Module1
Sub Main()
Console.WriteLine(DecConvert(27635, 16))
Console.WriteLine(DecConvert(27635, 8))
Console.WriteLine(DecConvert(27635, 2))
Console.ReadKey()
End Sub
Private Function DecConvert(ByVal N As Integer, ByVal D As Integer) As String
If (D <> 16) And (D <> 8) And (D <> 2) Then
Throw New ArgumentOutOfRangeException("D", "支支持十进制转二进制、八进制、十六进制!")
End If
Dim stack As New Stack()
Do
Dim residue As Integer
residue = N Mod D
Dim c As Char
c = IIf(residue < 10, Chr(residue + 48), Chr(residue + 55))
stack.Push(c)
N = N \ D
Loop While N <> 0
Dim s As String = ""
Do While stack.Count > 0
s &= stack.Pop.ToString
Loop
Return s
End Function
End Module