CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2000
    Location
    Olen, Belgium
    Posts
    2,477

    Converting binary to decimal

    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
    [email protected]

    The best way to escape a problem, is to solve it.
    Tom Cannaerts
    email: [email protected]
    www.tom.be (dutch site)

  2. #2
    Guest

    Re: Converting binary to decimal

    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


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured