Using DEC2BIN() with large numbers

后端 未结 9 1878
暖寄归人
暖寄归人 2020-12-31 06:28

I\'m trying to convert 4503599627370495 into binary in Excel. DEC2BIN() returns #NUM! error because DEC2BIN cannot handle such a large number.

Any thou

9条回答
  •  囚心锁ツ
    2020-12-31 06:58

    I modified AndruWitta's modification a little bit to handle negative numbers and return the binary number in two's complement format.

    Function DecToBin(ByVal DecimalIn As Variant, Optional NumberOfBits As Variant) As String
      DecToBin = ""
      DecimalIn = CDec(DecimalIn)
      If DecimalIn < 0 Then
      DecimalIn = -DecimalIn - 1
    
         Do While DecimalIn <> 0
            DecToBin = Trim$(Str$(Not DecimalIn - 2 * (Int(DecimalIn / 2 + 1)))) & DecToBin
            DecimalIn = Int(DecimalIn / 2)
        Loop
        DecToBin = Trim$(Str$(1)) & DecToBin
      Else
        Do While DecimalIn <> 0
            DecToBin = Trim$(Str$(DecimalIn - 2 * Int(DecimalIn / 2))) & DecToBin
            DecimalIn = Int(DecimalIn / 2)
        Loop
      End If
      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
    

提交回复
热议问题