Quick question, as I am REALLY new to visual basic, and frankly, am learning
as I go.
Is there a quick and dirty way to convert decimal numbers into binary. I
need this function for a program I'm working on, and would prefer not to
play with mods, etc.
Thanks for any assistance.
> Quick question, as I am REALLY new to visual basic, and frankly, am
> as I go.
> Is there a quick and dirty way to convert decimal numbers into binary. I
> need this function for a program I'm working on, and would prefer not to
> play with mods, etc.
You won't like it (for example, you can't give it to a teacher ...), but
here it is. But I do think you should use the " X mod 2" or "X and 1"
method instead :-)
Private Function MakeBin(Number As Variant) As String
Dim sOct As String, i As Integer, sResult As String
sOct = Oct$(Number) '-- Could bomb is the number is too large ....
For i = 1 To Len(sOct)
sResult = sResult & Mid$("000001010011100101110111", 1 + 3 *
Val(Mid$(sOct, i, 1)), 1)
MakeBin = sResult
Call like : Debug.Print MakeBin(1961)
On the off chance that you are serious, I've modified it here to use the
instead of the Str$ imbedded within a Trim$ (which was necessary in order to
Str$ default action of putting a leading blank space on positive numbers;
suffer from this "feature"). I've also provided the inverse (Bin2Dec)
function which also
works with numbers up to 96-bits.
'Decimal To Binary
' NOTE: You can limit the size of the returned
' answer by specifying the number of bits
Function Dec2Bin(ByVal DecimalIn As Variant, _
Optional NumberOfBits As Variant) As String
Dec2Bin = ""
DecimalIn = Int(CDec(DecimalIn))
Do While DecimalIn <> 0
Dec2Bin = Format$(DecimalIn - 2 * Int(DecimalIn / 2)) & Dec2Bin
DecimalIn = Int(DecimalIn / 2)
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
'Binary To Decimal
Function Bin2Dec(BinaryString As String) As Variant
Dim X As Integer
For X = 0 To Len(BinaryString) - 1
Bin2Dec = CDec(Bin2Dec) + Val(Mid(BinaryString, _
Len(BinaryString) - X, 1)) * 2 ^ X
MVP Visual Basic
Please respond only to the newsgroups so all can benefit.
"Michael Cebasek" <michael...@sympatico.ca> wrote in message