Click to See Complete Forum and Search --> : convert hex to binary?


klee168
January 18th, 2000, 03:05 PM
I need help on how to convert hex to binary in VB 6, thank you

johnpc1
January 19th, 2000, 07:34 AM
Put a Command Button on a Form name it cmdCalculate and add the follwing code to the
program


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