Convert Decimal Integer Values to Binary String in VB6

A small function to convert decimal integer values to a binary string. The number of bits can be optionally specified but this will be increased if insufficient.

Public Function DecToBin(DeciValue As Long, Optional NoOfBits As Integer = 8) _
As String
'********************************************************************************
'* Name : DecToBin
'* Date : 2003
'* Author : Alex Etchells
'*********************************************************************************
Dim i As Integer
'make sure there are enough bits to contain the number
Do While DeciValue > (2 ^ NoOfBits) - 1
NoOfBits = NoOfBits + 8
Loop
DecToBin = vbNullString
'build the string
For i = 0 To (NoOfBits - 1)
DecToBin = CStr((DeciValue And 2 ^ i) / 2 ^ i) & DecToBin
Next i
End Function

You might also like...

Comments

  1. 08 Sep 2006 at 13:06

    or may be a one liner like...

     

    Dim binaryString As String = Convert.ToString(numberToConvert, 2)

    Use PadLeft(n, "0") for required minimum length(n) of the output string.

    so it would look like

    Dim binaryString As String = Convert.ToString(numberToConvert, 2).PadLeft(n, "0")

    Prashant

     

  2. 08 Sep 2006 at 13:58
    The title (now edited) should have read 'in VB6'

  3. 08 Sep 2006 at 14:02
    Dim Number As Integer
    Dim BS As String

    Number = Val(Text1.Text)
    BS = ""
    While Number > 0
        BS = Number Mod 2 & BS
        Number = Number \ 2
    Wend
    Text2.Text = BS








  4. 13 Mar 2007 at 08:44

    Hi DoctorMahdi,

    How do I put BS into an array before display it into text2.text.  Thank you.

Leave a comment

Sign in or Join us (it's free).

Alex Etchells

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Beware of bugs in the above code; I have only proved it correct, not tried it.” - Donald Knuth