Binary to Decimal


Module Module8

    Function BINDEC(binary As String) As Long
        ' Validate input
        If String.IsNullOrEmpty(binary) Then
            Throw New ArgumentException("Input cannot be null or empty.")
        End If

        ' Ensure the string only contains 0s and 1s
        If Not System.Text.RegularExpressions.Regex.IsMatch(binary, "^[01]+$") Then
            Throw New ArgumentException("Input must be a binary string (only 0s and 1s).")
        End If

        ' Convert binary string to decimal
        Dim result As Long = 0
        For i As Integer = 0 To binary.Length - 1
            If binary(binary.Length - 1 - i) = "1"c Then
                result += CLng(Math.Pow(2, i))
            End If
        Next

        Return result
    End Function

    Sub Main8()
        Dim binaryString As String = "1101"
        Dim decimalValue As Long = BINDEC(binaryString)
        Console.WriteLine("Binary: " & binaryString & " → Decimal: " & decimalValue)
        ' Output: Binary: 1101 → Decimal: 13
    End Sub

End Module

Download 'Binary to Decimal.vb':

📥 Download binary-to-decimal.vb