vba BitsToLong

'Fast VBA function to converst binary string to a Long Integer:

Function BitsToLong&(bits$)
    Dim i&
    Static b() As Byte
    If LenB(bits) > 64 Then Exit Function
    If LenB(bits) = 64 Then
        b = bits
    Else
        b = String$(32 - Len(bits), "0") & bits
    End If
    For i = 2 To 62 Step 2
        BitsToLong = 2 * BitsToLong Or (b(i) Xor 48)
    Next
    If (b(0) Xor 48) Then BitsToLong = BitsToLong Or &H80000000
End Function

'-----------------------------------------------------------------------------

MsgBox BitsToLong("1")									'<--displays:  1    
MsgBox BitsToLong("10")									'<--displays:  2
MsgBox BitsToLong("0110")								'<--displays:  6
MsgBox BitsToLong("0100101")							'<--displays:  37
MsgBox BitsToLong("100000000000000000000")				'<--displays:  1048576
MsgBox BitsToLong("11111111111111111111111111111111")	'<--displays:  -1
    

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source