If the dec number is odd, the last bin digit will be 1. If it's even, the last digit will be 0 (make a note).
If the dec number is odd, substract 1, then divide by 2. If the result is also odd, then the next bin digit will be 1. If the result is even, your next digit will be 0.
Keep on dividing by 2 (and substracting 1 if odd) to get all the digits.
Bin to dec:
This is simpler. Mark c0,c1,c2,c3,... as the bin digits, starting from the tail. Then your dec will be:
Or, if you have a copy of MS Office, drop this these functions into a code module:
Code:
Public Function BinaryToDecimal(Binary As String) As Long
Dim n As Long
Dim s As Integer
For s = 1 To Len(Binary)
n = n + (Mid(Binary, Len(Binary) - s + 1, 1) * (2 ^ _
(s - 1)))
Next s
BinaryToDecimal = n
End Function
Public Function DecimalToBinary(DecimalNum As Long) As _
String
Dim tmp As String
Dim n As Long
n = DecimalNum
tmp = Trim(Str(n Mod 2))
n = n \ 2
Do While n <> 0
tmp = Trim(Str(n Mod 2)) & tmp
n = n \ 2
Loop
DecimalToBinary = tmp
End Function
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.