Convert Binary Number To Decimal Number

Author: Bob Butler

Form Code

Private Function BinaryToDecimal(ByVal BinValue As String) As Long
Dim lngValue As Long
Dim x As Long
Dim k As Long
k = Len(BinValue) ' will only work with 32 or fewer "bits"
For x = k To 1 Step -1 ' work backwards down string
  If Mid$(BinValue, x, 1) = "1" Then
    If k - x > 30 Then ' bit 31 is the sign bit
      lngValue = lngValue Or -2147483648# ' avoid overflow error
    Else
      lngValue = lngValue + 2 ^ (k - x)
    End If
  End If
Next x
BinaryToDecimal = lngValue
End Function

Private Sub Form_Load()
'Replace the "11001" below with the binary number you want to
'convert to decimal number

    MsgBox BinaryToDecimal("11001")
End Sub
   

Go Back