Matematické funkce VIII - Binární a decimální čísla

Funkce:

Function Bin(ByVal value As Long, Optional digits As Long = -1) As String

    
'Převod decimálního čísla na binární
    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

    If digits < 0 Then
        Bin = Mid$(result, 33 - exponent)
    Else
        Bin = Right$(result, digits)
    End If

End Function

Function BinToDec(value As String) As Long

    
'Převod binárního čísla na decimální
    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      
            Case 49      
                result = result Or Power2(exponent)
            Case Else
                Err.Raise 5      
        End Select
        exponent = exponent + 1
    Next

    BinToDec = result

End Function

Function Power2(ByVal exponent As Long) As Long

    
'Funkce pro mocninu 2, exponent musí být v intervalu [0;31]
    Static res(0 To 31) As Long
    Dim i As Long
    
    If exponent < 0 Or exponent > 31 Then Err.Raise 5
    
    If res(0) = 0 Then
        res(0) = 1
        For i = 1 To 30
            res(i) = res(i - 1) * 2
        Next
        res(31) = &H80000000
    End If
    
    Power2 = res(exponent)
        
End Function

Zpět

Autor: The Bozena