Results 1 to 20 of 22

Thread: Convert Decimal To Binary

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #16
    Knowledge Base Approver
    The King of Overkill!
    VBAX Master
    Joined
    Jul 2004
    Location
    Rochester, NY
    Posts
    1,727
    Location
    Hi sheeeng,

    You should just be able to use something like

    Public Function DecToBin(ByVal theDec As Variant) As String
    Dim i As Long
    For i = 31 To 0 Step -1
        DecToBin = DecToBin & CStr(Int(theDec / (2 ^ i)))
        theDec = theDec - Int(theDec / (2 ^ i)) * (2 ^ i)
    Next i
    End Function
    That will always produce a 32-character string of the binary equivalent of the decimal number. If you could possibly be converting a number larger than 4294967295, then you could use this, which will give you a string containing the binary number regardless of the size (well, up to 1.26765060022823E+30 but you could always increase the 99 if it could be bigger).

    Public Function DecToBin(ByVal theDec As Variant) As String
    Dim i As Long, j As Long
    For j = 99 To 0 Step -1
        If Int(theDec / (2 ^ j)) = 1 Then Exit For
    Next j
    For i = j To 0 Step -1
        DecToBin = DecToBin & CStr(Int(theDec / (2 ^ i)))
        theDec = theDec - Int(theDec / (2 ^ i)) * (2 ^ i)
    Next i
    End Function
    Let me know how it works for you!
    Matt
    Last edited by Aussiebear; 04-23-2023 at 04:39 PM. Reason: Adjusted the code tags

Posting Permissions

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