Click to See Complete Forum and Search --> : Converting binary to decimal


Cakkie
February 8th, 2000, 05:06 AM
Is there a function that converts a binary number into a decimal and the other way around?

eg: 10011101 should return 157
eg: 156 should return 10011100

regards

Tom Cannaerts
slisse@planetinternet.be

The best way to escape a problem, is to solve it.

February 8th, 2000, 06:22 AM
Here are two functions for the conversion
The ToBinary Function comes from the Microsoft KnowledgeBase and the ToDecimal is one I've just made up so that may require some work Ok

Function ToDecimal(ToConvert) as Long
ToDecimal = 0
for i = 0 to len(ToConvert) - 1
If mid(CStr(ToConvert), len(ToConvert) - i, 1) = 1 then
ToDecimal = ToDecimal + 2 ^ i
else
End If
next
End Function
Function ToBinary(ToConvert) as Long

Dim i as Long, x as Long, bin as string
Const maxpower = 30 ' Maximum number of binary digits supported.
'text1.MaxLength = 9 ' Maximum number of decimal digits allowed.
'text2.Enabled = false ' Prevent typing in second text box.
bin = "" 'Build the desired binary number in this string, bin.
x = Val(ToConvert) 'Convert decimal string in text1 to long integer

If x > 2 ^ maxpower then
MsgBox "Number must be no larger than " & Str$(2 ^ maxpower)

Exit Function
End If

' Here is the heart of the conversion from decimal to binary:

' Negative numbers have "1" in the 32nd left-most digit:
If x < 0 then bin = bin + "1" else bin = bin + "0"

for i = maxpower to 0 step -1
If x And (2 ^ i) then ' Use the logical "AND" operator.
bin = bin + "1"
else
bin = bin + "0"
End If
next
ToBinary = bin ' The bin string contains the binary number.
End Function



Hope this helps