Using DEC2BIN() with large numbers

后端 未结 9 1954
暖寄归人
暖寄归人 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 07:03

    This function will convert as big as a Double can hold. I didn't try it with negative values, though.

    Function cn(ByVal n As Double, ByVal s As Double)
      'n the number to convert
      's the numberic system to convert to.
      'This function can convert to binary all the way to the length of the
      'digits string and all in between.
    
      Dim x As Double  'The exponent without decimals
      Dim xx As Double 'The exponent with decimals, if any
      Dim r As String  'The return string
      Dim p As Integer 'Posistion of the digit in the return string
      Dim L As Long    'Length of the string return string
      Dim d            '(d+1) because mid() does not accept 0.
                       'The position of the digit in the digits string.
     Dim v As Double   'The numeric value of the position 
                       'of the digit in the return string
      Dim digits As String
      digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Start:
    
      If n > 0 Then
         xx = Log(n) / Log(s)
         x = Int(xx)
      End If
      p = x + 1
      If r = "" Then
        r = String(p, "0")
        L = p
      End If
      v = s ^ x
      d = n \ v
      Mid(r, L - x, 1) = Mid(digits, d + 1, 1)
      n = n - (v * d)
      If n <> 0 Then GoTo Start
      cn = r
    End Function
    

提交回复
热议问题