Using DEC2BIN() with large numbers

后端 未结 9 1936
暖寄归人
暖寄归人 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条回答
  •  Happy的楠姐
    2020-12-31 07:04

    Normally when I need to know the binary of a decimal value, it is always interesting to see the hexadecimal value. The function does not use MOD or HEX() for the big number since Microsoft limited it, so it is done manually for very large numbers.

    Bino(Value,Bytes)

    Value can be any integer decimal number or a cell contained it, small or superbig. Bytes is optional, standard 2, automatic.

    =Bino(A1,4)

    The number or bytes and bits presented is automatic based on its value, standard minimum of 2 bytes, but you can pad with extra zero bytes at left, using the optional bytes argument. The example above will show A1 with 4 bytes and 32 bits, even if A1 contains a single numeric digit, or will use more bytes and bits if larger than 4.

    =Bino(A1)

    Will show A1 with a minimum of 2 bytes and 16 bits, or larger if necessary. For better visualization, binary format has nibbles separated by "-" and bytes by "|"

    =Bino(129) = 0x0081 = 0000-0000|1000-0001

    =Bino(129,1) = 0x81 = 1000-0001

    =Bino(257,1) = 0x0101 = 0000-0001|0000-0001

    The function is rigged to insert Error messages into the CELL in case the number is negative or bytes > 10. Can be easily removed or changed.

    It helped me while testing VBA simulating lots of math for optimization code for 8 bits microcontrollers (AVR) assembly, creating routines for Sin(x) and Ln(x) with 16 bits precision.

    Public Function Bino(ByVal Valo As Double, Optional ByVal Bytes As Long = 2) As String
    Dim Conta
    Dim Resul as String
    Dim Bits
    Dim SA As Double
    Dim SB As Double
    Dim SX As String
    
    If Valo < 0 Then
       Bino = "[Err: Negative]"
       Exit Function
       End If
    
    If Bytes > 4 Then
       Bino = "[Err: Bytes > 10]"
       Exit Function
       End If
    
    ValoHex = ""
    SB = Valo
    Do While SB > 1
       SA = SB / 16
       ValoHex = Hex(Int(16 * (SA - Int(SA)))) & ValoHex
       SB = SA
    Loop
    
    If Len(ValoHex) Mod 2 = 1 Then ValoHex = "0" & ValoHex
    Zeroz = Bytes * 2 - Len(ValoHex)
    If Zeroz = 2 Then ValoHex = "00" & ValoHex
    If Zeroz = 4 Then ValoHex = "0000" & ValoHex
    ValoHexLen = Len(ValoHex)
    ValoHex = "0x" & ValoHex
    
    If Bytes < ValoHexLen Then Bytes = ValoHexLen / 2
    Bits = Bytes * 8 - 1
    For Conta = 0 To Bits
        Div = ""
        If Conta And Conta Mod 4 = 0 Then Div = "-"
        If Conta And Conta Mod 8 = 0 Then Div = "|"
        If Int(Valo / 2) = Valo / 2 Then Bitt = 0 Else Bitt = 1
        Resul = Bitt & Div & Resul
        Valo = Int(Valo / 2)
    Next Conta
    
    Resul = ValoHex & " = " & Resul
    Bino = Resul
    
    End Function
    

提交回复
热议问题