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.
Hello Michael,
> 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.
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)
Next i
MakeBin = sResult
End Function
Call like : Debug.Print MakeBin(1961)
Regards,
Rudy Wieser
---------------------------------------
On the off chance that you are serious, I've modified it here to use the
Format$ function
instead of the Str$ imbedded within a Trim$ (which was necessary in order to
account for
Str$ default action of putting a leading blank space on positive numbers;
Format$ doesn't
suffer from this "feature"). I've also provided the inverse (Bin2Dec)
function which also
works with numbers up to 96-bits.
Rick
'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)
Loop
If Not IsMissing(NumberOfBits) Then
If Len(Dec2Bin) > NumberOfBits Then
Dec2Bin = "Error - Number exceeds specified bit size"
Else
Dec2Bin = Right$(String$(NumberOfBits, _
"0") & Dec2Bin, NumberOfBits)
End If
End If
End Function
'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
Next
End Function
--
Randy Birch
MVP Visual Basic
http://www.mvps.org/vbnet/
Please respond only to the newsgroups so all can benefit.
"Michael Cebasek" <michael...@sympatico.ca> wrote in message
news:B_1J9.2572$lL6.3...@news20.bellglobal.com...