In: Mechanical Engineering
write a VBA code to convert an arbitrary positive binary fractional number (0< number<1) to equivalent decimal number. the code should acquire the binary fraction number in the format"0.xxxxxx"from input box, then return the equivalent decimal number in a message box. in the code, you may need to use VBA function "mid(_,_,_)" to pick up a specific symbols or characters from a string. you can use below conversion as benchmark to verify and debug your code:
(0.1011)2 = (0.6875)10
Sub Binary_to_Decimal()
Dim B, B1, B2 As String
Dim i, A As Integer
Dim A1, D As Double
B = InputBox("please enter the Fractional binary
number(0.xxxxxx)")
'B = 0.1011
B1 = Mid(B, 1, 1)
B2 = Mid(B, 2, 1)
If B1 = 0 And B2 = "." Then
D = 0
For i = 1 To Len(B) - 2
A = Mid(B, i + 2,
1)
A = CInt(A)
If A = 0 Or A = 1
Then
A1 =
Application.WorksheetFunction.Power(2, -i)
D = D + A * A1
Else: GoTo 1
End If
Next i
MsgBox ("The equivalent Decimal number for given
Fraction Binary number is equal to " & D)
Else
1 MsgBox ("Input is not in
correct format")
End If
End Sub