How do you convert decimals to binary?

CivEmperor

Warlord
Joined
Sep 22, 2003
Messages
158
Location
Canton Ohio
How do you convert decimals to binary and vica versa?
 
Dec to bin conversion:

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:

dec = c0 * 2^0 + c1 * 2^1 + c2 * 2^2 + ...


Hope that helps
 
it does thanks
 
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
 
How about doing that recursively, ainwood? ;)
 
Top Bottom