View Single Post
  #20   Report Post  
Posted to microsoft.public.excel.worksheet.functions
Dana DeLouis[_3_] Dana DeLouis[_3_] is offline
external usenet poster
 
Posts: 690
Default BIN2DEC conversion for large binary numbers

On 12/15/2009 9:28 PM, Rick Rothstein wrote:
Below is a UDF that will handle up to a 96-bit binary number (decimal
value 79228162514264337593543950335) which I'm guessing is way more than
you will ever need.<g The code is efficient (looping only as many times
as necessary to process the passed in binary value), so don't worry
about it being able to handle such a large binary value. The function
returns a real numeric value up to 9999999999 after which it returns
text representations of the calculated number.

Function BinToDec(BinaryString As String) As Variant
Dim X As Integer
Const TwoToThe48 As Variant = 281474976710656#
For X = 0 To Len(BinaryString) - 1
If X 48 Then
BinToDec = CDec(BinToDec) + Val(Mid(BinaryString, _
Len(BinaryString) - X, 1)) * _
TwoToThe48 * CDec(2 ^ (X - 48))
Else
BinToDec = CDec(BinToDec) + Val(Mid(BinaryString, _
Len(BinaryString) - X, 1)) * CDec(2 ^ X)
End If
Next
If Len(BinToDec) 10 Then BinToDec = CStr(BinToDec)
End Function



Hi. Just throwing out another idea. Len(BinaryString) is more of a
constant (calculated each loop), and power (ie 2^x) is sometimes
considered "slower."
This has no error checking.

Function Bin2Dec(str As String)
Dim S As String
Dim P As Long
Dim K As Variant
Dim Ans As Variant

S = StrReverse(str)
K = CDec(1)

For P = 1 To Len(S) - 1
Ans = Ans + Val(Mid$(S, P, 1)) * K
K = K * 2
Next P
Bin2Dec = Ans + Val(Mid$(S, P, 1)) * K
End Function



Sub TestIt()
Dim S As String
S = WorksheetFunction.Rept("1", 96)
Debug.Print Bin2Dec(S)

Mid(S, 3, 1) = 0
Debug.Print Bin2Dec(S)

Mid(S, 96, 1) = 0
Debug.Print Bin2Dec(S)

Mid(S, 95, 1) = 0
Debug.Print Bin2Dec(S)
Debug.Print "= = = = = = = ="
End Sub


Returns:

79228162514264337593543950335
69324642199981295394350956543
69324642199981295394350956542
69324642199981295394350956540
= = = = = = = =

Again, just an idea.
Dana DeLouis