2014-03-01 42 views
9

我試圖在Excel中將4503599627370495轉換爲二進制。 DEC2BIN()返回#NUM!錯誤,因爲DEC2BIN無法處理這麼大的數字。大量使用DEC2BIN()

有關我如何能夠使其工作的任何想法?

+0

在一般情況下,不容易。在工作表上,Excel會將其存儲爲4503599627370490(最後一位數字丟失)。您可以將其存儲爲文本,但轉換爲BIN會變得很難看。 Tushar Mehta有一個很好的[page](http://www.tushar-mehta.com/misc_tutorials/project_euler/LargeNumberArithmetic.htm),詳細介紹了在VBA中處理大量數學問題。 –

+0

http://dailydoseofexcel.com/archives/2005/12/02/decimal-to-binary/ –

+0

看到這個答案:http://stackoverflow.com/a/24388218/2396122 – RKG

回答

4

見VBA張貼在這裏

' The DecimalIn argument is limited to 79228162514264337593543950245 
' (approximately 96-bits) - large numerical values must be entered 
' as a String value to prevent conversion to scientific notation. Then 
' optional NumberOfBits allows you to zero-fill the front of smaller 
' values in order to return values up to a desired bit level. 
Function DecToBin(ByVal DecimalIn As Variant, Optional NumberOfBits As Variant) As String 
    DecToBin = "" 
    DecimalIn = CDec(DecimalIn) 
    Do While DecimalIn <> 0 
    DecToBin = Trim$(Str$(DecimalIn - 2 * Int(DecimalIn/2))) & DecToBin 
    DecimalIn = Int(DecimalIn/2) 
    Loop 
    If Not IsMissing(NumberOfBits) Then 
    If Len(DecToBin) > NumberOfBits Then 
     DecToBin = "Error - Number too large for bit size" 
    Else 
     DecToBin = Right$(String$(NumberOfBits, "0") & _ 
     DecToBin, NumberOfBits) 
    End If 
    End If 
End Function 
+0

注意這個答案也提供在http ://stackoverflow.com/questions/24387894/decimal-to-binary-conversion-for-large-numbers-in-excel/24388495#24388495 – JustinJDavies

+0

你應該將其標記爲重複,而不是發佈2個重複的答案那樣 –

6

感謝名單JustinDavies - 這是我需要的,但如果通過了-ve數它進入一個死循環。我的修改:

Function DecToBin(ByVal DecimalIn As Variant, Optional NumberOfBits As Variant) As String 
    DecToBin = "" 
    DecimalIn = CDec(DecimalIn) 
    If DecimalIn < 0 Then 
    DecToBin = "Error - Number negative" 
    Exit Function 
    End If 
    Do While DecimalIn <> 0 
    DecToBin = Trim$(Str$(DecimalIn - 2 * Int(DecimalIn/2))) & DecToBin 
    DecimalIn = Int(DecimalIn/2) 
    Loop 
    If Not IsMissing(NumberOfBits) Then 
    If Len(DecToBin) > NumberOfBits Then 
     DecToBin = "Error - Number too large for bit size" 
    Else 
     DecToBin = Right$(String$(NumberOfBits, "0") & _ 
     DecToBin, NumberOfBits) 
    End If 
    End If 
End Function 
0

對於正數4,294,967,295,您可以使用此answer給出的公式。如果你需要更大的數字,他的答案可以延長。