Unsigned Numbers (Binary Arithmetic)
Hi Everybody,
I have written two functions which allow you to convert binary numbers to decimals and decimals to binary. I haven't yet added any support for unsigned numbers, but soon will. Meanwhile if there are any ideas for shrinking the code, they are most welcome.
Cheers!
Abhijit
Code:
Private Function To_Decimal(vValue As Variant) As Long
Dim sValue As String
Dim lLenValue As Long
Dim lReturnVal As Long
Dim aIndices(8) As Long
aIndices(0) = 2 ^ 0
aIndices(1) = 2 ^ 1
aIndices(2) = 2 ^ 2
aIndices(3) = 2 ^ 3
aIndices(4) = 2 ^ 4
aIndices(5) = 2 ^ 5
aIndices(6) = 2 ^ 6
aIndices(7) = 2 ^ 7
sValue = CStr(vValue)
lLenValue = Len(sValue)
If lLenValue < 8 Then
Do Until Len(sValue) = 8
sValue = "0" & Left(sValue, Len(sValue))
Loop
End If
Dim iIndexPosition As Integer
iIndexPosition = 0
' Now Start from the most side bit and decrement
For lLenValue = 8 To 1 Step -1
Debug.Print sValue & " ---> " & Mid(sValue, lLenValue, 1)
lReturnVal = lReturnVal + (CLng(Mid(sValue, lLenValue, 1)) * aIndices(iIndexPosition))
iIndexPosition = iIndexPosition + 1
Next lLenValue
To_Decimal = lReturnVal
End Function
Private Function To_Binary(iInputNo As Integer) As String
Dim aBitValues(7) As Integer
aBitValues(0) = 128
aBitValues(1) = 64
aBitValues(2) = 32
aBitValues(3) = 16
aBitValues(4) = 8
aBitValues(5) = 4
aBitValues(6) = 2
aBitValues(7) = 1
Dim iArrCounter As Integer
Dim sReturnValue As String
For iArrCounter = 0 To UBound(aBitValues)
If iInputNo < aBitValues(iArrCounter) Then
sReturnValue = sReturnValue & "0"
Else
sReturnValue = sReturnValue & "1"
iInputNo = iInputNo - aBitValues(iArrCounter)
End If
Next iArrCounter
To_Binary = sReturnValue
End Function
:cool: