Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleConvert decimal values into binary and vice versa
Keywordsdecimal, binary, conversion, convert
CategoriesAlgorithms, Software Engineering
 
Thanks to Yaron Budowski.

Use powers of 2 to build the decimal number from a binary string. Extract powers of 2 from the decimal value to convert it into a binary string.

 
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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated