Search code examples
algorithmsequencesbasicexponent

Convert powers of 2 into linear sequence without Logarithms


Without using logarithms, how can I convert a sequence of powers of 2 into linear integers in BASIC?

Input:  0, 1, 2, 4, 8, 16, 32, 64, 128
Output: 0, 1, 2, 3, 4,  5,  6,  7,   8

Solution

  • Yes, you convert the number to binary. For example, the binary value of 64 is: 1000000. Since the 1 is in the seventh position you know the required value is 7. Here is a Visual Basic program to do this:

    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
    

    In this algorithm the values are appended to a string but you can just as well store them in an array of 1s and 0s. Also note that you can always get the power of two by the length of the string produced by the algorithm above. For example, the length of the string "1001010" is 7 which means the number is between 64 and 127.