Konversi Basis


‘ untuk menghitung 2 pangkat n
Function Power2(ByVal exponent As Long) As Long
    Static result(0 To 31) As Long, i As Integer
    If result(0) = 0 Then
        result(0) = 1
        For i = 1 To 30
            result(i) = result(i – 1) * 2
        Next
        result(31) = &H80000000
    End If
    Power2 = result(exponent)
End Function

‘ Konversi dari desimal ke biner.
Function Bin(ByVal value As Long) As String
    Dim result As String, exponent As Integer
    result = String$(32, “0”)
    Do
        If value And Power2(exponent) Then
            Mid$(result, 32 – exponent, 1) = “1”
            value = value Xor Power2(exponent)
        End If
        exponent = exponent + 1
    Loop While value
    Bin = Mid$(result, 33 – exponent)  ‘ hilangkan leading zero.
End Function

‘ Konversi dari biner ke desimal
Function BinToDec(value As String) As Long
    Dim result As Long, i As Integer, exponent As Integer
    For i = Len(value) To 1 Step -1
        Select Case Asc(Mid$(value, i, 1))
            Case 48      ‘ “0”, gak perlu ngapa2in.
            Case 49      ‘ “1”, tambah dengan 2 pangkat n.
                result = result + Power2(exponent)
            Case Else
                Err.Raise 5  ‘ Invalid procedure call or argument
        End Select
        exponent = exponent + 1
    Next
    BinToDec = result
End Function

Private Sub Form_Load()
  MsgBox Bin(43)     ‘menghasilkan 101011
  MsgBox BinToDec(“10101011”)  ‘menghasilkan 171
  End
End Sub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s