VBA自定义函数:可将特别大的十进制数转换成二进制数

2023-12-26 16:13:46 浏览数 (2)

标签:VBA

Excel中的DEC2BIN()函数可以将十进制数字转换成二进制数字,但其存在局限性。本文介绍的VBA用户定义函数可以将-2147483647到2147483647(2^31-1)之间的十进制数值转换成二进制整数。如果要转换的数值为负,则返回二进制补码值(高位设置为1)。如果numBits小于表示数字所需的位数,则返回#NUM!。

这个自定义函数的代码如下:

代码语言:javascript复制
Function LongDec2Bin(ByVal nIn As Long, _
         Optional nBits As Long = 0&) As Variant
 Dim nReqBits As Long
 Dim sOut As String
 Dim sBit As String
 Dim bNeg As Boolean
 Dim i As Long
 If nIn < 0& Then
   bNeg = True
   nIn = -(nIn   1&)
 End If
 If nIn = 0& Then
   nReqBits = 1&
 Else
   nReqBits = Int(Log(nIn) / Log(2&))   1& - bNeg
 End If
 If nBits <= 0& Then nBits = nReqBits
 If nBits >= nReqBits Then
   If bNeg Then
     sOut = String(nBits, "1")
     sBit = "0"
   Else
     sOut = String(nBits, "0")
     sBit = "1"
   End If
   For i = nBits To (nBits - nReqBits   1&) Step -1
     If (nIn - 2& * (nIn  2&)) > 0 _
         Then Mid(sOut, i, 1&) = sBit
     nIn = nIn  2&
   Next i
   LongDec2Bin = sOut
 Else
   LongDec2Bin = CVErr(xlErrNum)
 End If
End Function

注:代码整理自mcgimpsey.com,供有兴趣的朋友参考。

0 人点赞