Bin - 將十進制轉成二進制 感謝網友神行者提供!

有 HEX(Number) 把base10 to base 16     OCT(number) 把base10 to base 8    就是沒有 BIN(number) 把base10  to base2

Private Function BIN(Key)
Dim i As Integer
Dim BinStr, Nbin As String
Key = Key / 2
Do Until (Key <= 1)
  For i = 1 To Len(Key)
    If Mid(Key, i, 1) = "." Then
      BinStr = BinStr + "1"
      GoTo RA
      End If
  Next i
  BinStr = BinStr + "0"
RA:
  Key = Int(Key) / 2
  If Key = 1 Then BinStr = BinStr + "01"
  If Key < 1 Then BinStr = BinStr + "1"
Loop
For i = 1 To Len(BinStr)
  Nbin = Nbin + Mid(BinStr, Len(BinStr) + 1 - i, 1)
Next i
BIN = Nbin
End Function

另一個是德本立寫的,方法和以上的函數略有不同:

Function TTB(n As Integer) As String
Dim i, j As Integer
i = 0
Do Until 2 ^ i > n
i = i + 1
Loop
For j = i - 1 To 0 Step -1
If n >= 2 ^ j Then
TTB = TTB & "1"
n = n - 2 ^ j
Else
TTB = TTB & "0"
End If
Next j
End Function

使用範例:準備Text1、Text2、Command1,貼上程式碼,執行後將十進制的數字輸入到Text1,再按Command1,二進制的數字就會顯示在Text2中。

Option Explicit

Private Sub Command1_Click()
Text2 = TTB(Text1)
End Sub

Function TTB(n As Integer) As String
Dim i, j As Integer
i = 0
Do Until 2 ^ i > n
i = i + 1
Loop
For j = i - 1 To 0 Step -1
If n >= 2 ^ j Then
TTB = TTB & "1"
n = n - 2 ^ j
Else
TTB = TTB & "0"
End If
Next j
End Function


上一頁