Results 1 to 2 of 2

Thread: VB Snippet - Convert Decimal to Binary

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Aug 2000
    Location
    IN SILENCE
    Posts
    6,441

    VB Snippet - Convert Decimal to Binary

    VB Code:
    1. Private Function DecToBin(ByVal Dec As Double) As Double
    2.  
    3.     Dim strTValue As String, strValue As String
    4.  
    5.     Do
    6.  
    7.         strTValue = Str(Dec Mod 2)
    8.  
    9.         strValue= strTValue & strValue
    10.  
    11.         Dec = IIf(Right(Str(Dec), 2) = ".5", Dec - 0.5, IIf(Dec Mod 2 > 0, Dec - 1, Dec)) / 2
    12.    
    13.     Loop Until Dec = 0
    14.    
    15.     DecToBin = Val(strValue)
    16.  
    17. End Function
    Remaining quiet down here !!!

    BRAD HAS GIVEN ME THE ULTIMATIVE. I have chosen to stay....

  2. #2
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,802
    Nice... but for large numbers it returns something like: 1.001101011E+28 and I don't think anyone wants that...

    I modified your code to return the number as a string, and the result is better
    VB Code:
    1. Private Function DecToBinStr(ByVal Dec As Double) As String
    2.     Dim strTValue As String, strValue As String
    3.    
    4.     Do
    5.         strTValue = Str(Dec Mod 2)
    6.         strValue = strTValue & strValue
    7.        
    8.         Dec = IIf(Right(Str(Dec), 2) = ".5", Dec - 0.5, IIf(Dec Mod 2 > 0, Dec - 1, Dec)) / 2
    9.     Loop Until Dec = 0
    10.    
    11.     DecToBinStr = Replace(strValue, " ", "")
    12. End Function

    Example of what i'm talking about

    VB Code:
    1. Debug.Print DecToBin(324534523)       ' returns 1.001101011E+28
    2. Debug.Print DecToBinStr(324534523)  ' returns 10011010110000000000011111011

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