Using DEC2BIN() with large numbers

后端 未结 9 1940
暖寄归人
暖寄归人 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:18

    I needed a VBA function to convert Excel decimal integers to binary since MS failed me, yet again. I came up with the following, but I had to accept a string of ones & zeros as output, which was OK for me. It uses log base 2 which may be unique (or not?) and works for all positive integers as-is.

    Function Dec_Bin(dx As Integer) As String
        Dim x As Integer
        Dim y As Long
        Dim z As Integer
        Dim zz As Double
        Dim ch As String
        Dim str As String, s1 As String
        Dim lead As Boolean
    
        ch = String(15, "0")
    '    Stop
        zz = Log(dx) / Log(2)
        z = Fix(zz)
        y = dx - 2 ^ z
        z = 15 - z
        Mid(ch, z, 1) = "1"
        While y > 0
            zz = Log(y) / Log(2)
            z = Fix(zz)
            y = y - 2 ^ z
            z = 15 - z
            Mid(ch, z, 1) = "1"
            Wend
    
        ch = ch & "B"
        Dec_Bin = ch
    End Function
    

提交回复
热议问题