Binary <--> Numeric conversion - THE RIGHT WAY!!!! {Updated!}
I came in here looking for a quick and dirty method of converting numeric values to binary, and back again. I don't mean to be rude, people, but if you don't know what you're doing, don't upload the code. I poured through well over 2 dozen horribly ugly "methods" of conversion that all involved nested loops, select case, if/then trees, and all other sorts of nonsense. Finally, I gave up and wrote it myself. Once you understand the maths that go into making a binary number, you'll understand how simple this code really is. It can manage to convert any Long Integer to binary, and back again, quick, easy, and with a minimum of overhead. I'm sure there's probably even APIs to do this, now, but they likely wouldn't be available on legacy systems, and this method will work in any language.
Original Author: Javin
Code
'*
'*
'*
'***NOTE: This is the highly optimized code. If you haven't been following this uphill battle, you won't get it. But this is (I believe) the fastest method of finding binary values through VB. - This was a collective effort of myself and
'Kaverin (Of #VB on DalNet)
'*
Public Function ConvertToBinary(ByVal Number As Long, ByVal Bits As Byte) As String
Dim intCount As Byte
ConvertToBinary = String$(Bits, "0")
For intCount = 1 To Bits
If Number And 1 Then Mid$(ConvertToBinary, Bits + 1 - intCount, 1) = "1"
Number = Number 2
Next intCount
End Function
Public Function ConvertFromBinary(ByVal Binary As String) As Long
Dim intCount As Integer
For intCount = Len(Binary) To 1 Step -1
If Mid$(Binary, intCount, 1) = "1" Then ConvertFromBinary = ConvertFromBinary + (&H2 ^ (Len(Binary) - intCount))
Next intCount
End Function
Loading Comments ...
Comments
No comments have been added for this post.
You must be logged in to make a comment.