Public Function BinToDec(ByVal strBinary As String, _
Optional blSigned As Boolean = True) As Currency
'Converts the passed binary string into a decimal value. blSigned is defaulted to true, which
'means the returned result will be "signed" using the left most bit of a 2, or 4 byte string
'as the sign. Note: for signed systems, it is imperative to know the byte size you are
'working with, in MSAccess negatives values must be in at least 2 bytes,
'For the scope of this code, there is a 4 byte maximum.
'
'Example Usage:
'-----------------
'BinToDec("1100") -> 12
'BinToDec("1100,True") -> 12
'BinToDec("10001100",True) -> 140
'BinToDec("11111111 11111111") -> 65535
'BinToDec("01111111 11111111,True") -> 32767
'BinToDec("11111111 11111111",True) -> -1
'BinToDex("10000000 00000000",True) -> -32768
'--------------------------------------------------------------------------------
Dim x As Integer 'An index
Dim intLength As Integer 'the length of the passed string passed
Dim curValueOffset As Currency 'The value of the offset (used for negatives)
Dim curValue As Currency 'The numeric value be returned
Dim intPadSize As Integer
Dim strTemp As String 'A temp string
'Strip invalid characters and find the length of the passed string
For x = 1 To Len(strBinary)
If InStr("01", Mid(strBinary, x, 1)) > 0 Then
strTemp = strTemp & Mid(strBinary, x, 1)
End If
Next x
strBinary = strTemp
'Test for too long of binary value, plus pad with "0"'s if less that 32
If Len(strBinary) > 32 Then
MsgBox "Overflow", vbCritical, "Error"
Exit Function
Else
If Len(strBinary) > 16 Then
intPadSize = 32
Else
intPadSize = 16
End If
End If
strBinary = String(intPadSize - Len(strBinary), "0") & strBinary
intLength = Len(strBinary)
'Loop through the right most bits, saveing the last one for later
'Note the loop counter increments up, but the character evaluation is
'from the right to the left, the the left most bit is not checked in
'this loop
For x = 0 To intLength - 2
If Mid(strBinary, intLength - x, 1) = "1" Then
curValue = curValue + 2 ^ x
End If
Next x
'Evaluate the leftmost bit and return the result
If Left(strBinary, 1) = "1" Then
If blSigned = True Then
BinToDec = curValue - 2 ^ (intLength - 1)
Else
BinToDec = curValue + 2 ^ (intLength - 1)
End If
Else
BinToDec = curValue
End If
End Function