江蘇省二級VB常用算法(四)進制轉化- - |
VB常用算法(四)進制轉化- -曹蘇群 http://caosuqun.bokee.com Tag: 進制轉化 算法
1、算法說明1) 十進制正整數m轉換為R(2-16)進制的字符串。 思路: 將m不斷除r取余數,直到商為0,將余數反序即得到結果。 算法實現: Private Function Tran(ByVal m As Integer, ByVal r As Integer) As String Dim StrDtoR As String, n As Integer Do While m <> o n = m Mod r m = m \ r If n > 9 Then StrDtoR = Chr(65 + n - 10) & StrDtoR Else StrDtoR = n & StrDtoR End If Tran = StrDtoR End Function
2) R(2-16)進制字符串轉換為十進制正整數。 思路:R進制數每位數字乘以權值之和即為十進制數。 算法實現: Private Function Tran(ByVal s As String, ByVal r As Integer) As integer Dim n As Integer, dec As Integer s = UCase(Trim(s)) For i% = 1 To Len(s) If Mid(s, i, 1) >= "A" Then n = Asc(Mid(s, i, 1)) - Asc("A") + 10 Else n = Val(Mid(s, i, 1)) End If dec = dec + n * r ^ (Len(s) - i) Next i Tran = dec End Function
解題技巧 進制轉化的原理要清楚,同時編寫代碼時候要留意16進制中的A-F字符的處理。
2、實戰練習1) 補充代碼(2002秋二(9)) 本程序是把給定的二進制整數轉換為八進制整數。 Private Sub Command1_Click() Dim a As String, b As String, c As String Dim L As Integer, m As Integer, n As Integer a = InputBox("請輸入一個二進制數", "輸入框") (1) a = String(L, "0") & a (2) For m = 1 To n / 3 b = Mid(a, 3 * m - 2, 3) (3) Next m Text1.Text = c End Sub
Private Function zh(s As String) As String Dim i As Integer, n As Integer, p As Integer p = 1 For i = 2 To 0 Step -1 (4) p = p + 1 Next i zh = Str(n) End Function
2) 補充代碼(2001春二(7)) 下面程序是把給定的16進制正整數轉換為10進制數。 Option Explicit
Private Sub Form_Click() Dim St As Integer, Dem As Long St=InputBox("輸入一個十六進制數") Dem=Convert(St) Print St; ">="; Dem End Sub
Private Function Convert(S As String)As Long Dim N As Integer, I As Integer,Substring As String*1 Dim P As long, K As Long,Asc1 As Integer N= (1) P=16^N For I=1 To N P=P/16 Substring= (2) Select Case Substring Case "0" To "9" K=K+P*Val(Substring) Case (3) Asc1=Asc(Substring)-Asc("A")+10 (4) End Select Next I (5) End Function |