Advertisement
ASP_Volume2 VB function enhancement #27592

Binary String<--> Numeric conversion - THE RIGHT WAY!!!! {Updated!}

First some clarification: This takes a number (say, 65) and the number of bits you want returned (say 8) and returns a STRING of 1's and 0's (such as "01000001"). Also converts the other way, too. Since VB doesn't have any bitshifting capability, this MIGHT be the only way to do it. (If someone has a better method, by all means PLEASE let me know.) I came in here looking for a quick and dirty method of doing this. 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. Note that this is marked as "Advanced" code. If you can't figure out how to use it, that's on you. In reality, it's pretty straightforward.

AI

Ringkasan AI: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Kode Sumber
original-source
'*
'*
'*
'***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
Komentar Asli (3)
Dipulihkan dari Wayback Machine