DecToBinary




Option Explicit
Dim decml As Double
Dim jbinary As String
Dim digit As Single, power As Single
Dim h As Integer, i As Integer, jbin As Integer
Dim j As Integer, k As Integer

Private Sub cmdCalculate_Click()

decml = 16 'this is the number to convert

DecBin decml, jbin ' convert from decimal to binary


Print "Decimal ="; BinDec(jbin) ' convert from binary to decimal

Print "binary = "; jbin ' display the result

Print "Hex = "; Hex(decml)

Print "OCTAL = "; Oct$(decml)
End Sub
' converts a string of binary digits to its decimal equivalent

Static Function BinDec(jbinary)
Dim digit, power, i, jbin As Integer
decml = 0: jbin = 0
jbinary = UCase(jbinary)
For i = Len(jbinary) To 1 step -1 ' convert from binary to decimal
digit = Asc(Mid(jbinary, i, 1)) - 48
If digit < 0 Or digit > 1 Then decml = 0: Exit For
decml = decml + digit * 2 ^ (power)
power = power + 1
Next i
BinDec = decml
End Function

' converts a decimal value to an equivalent string of binary digits

Static Sub DecBin(decml, jbin)

jbin = ""
h = Hex(decml) ' convert from decimal to hexadecimal
For i = 1 To Len(h)
digit = InStr("0123456789ABCDEF", Mid(h, i, 1)) - 1
If digit < 0 Then jbin = "": Exit For
j = 8: k = 4
Do ' convert from hexadecimal to binary
jbin = jbin + Right$(Str((digit \ j) Mod 2), 1)
j = j - (j \ 2): k = k - 1
If k = 0 Then Exit Do
Loop While j
Next i
End Sub










( dectobinary.html )- by Paolo Puglisi - Modifica del 17/12/2023