|
|
|
Option Explicit
'最大の2のべき乗の値を探す
Private Function Ex2noBeki(deci As Long) As Integer
Dim i As Integer
i = 0
Do
'deciより大きい
If deci < 2 ^ i Then
'その一つ前のべき乗
Ex2noBeki = i - 1
Exit Function
End If
i = i + 1
Loop
End Function
'10進数を2進数に変換
Public Function ExDeciToBin(deci As Long) As String
Dim ln As Long
Dim stemp As String
Dim i As Integer
Dim count As Integer
stemp = "1"
'deciより小さい、最大の2のべき乗の値を探す
count = Ex2noBeki(deci)
ln = deci - 2 ^ count
'筆算と同じように繰り返す
For i = count - 1 To 0 Step -1
If ln < 2 ^ i Then
stemp = stemp & "0"
Else
stemp = stemp & "1"
ln = ln - (2 ^ i)
End If
Next i
ExDeciToBin = stemp
End Function
Private Sub CommandButton1_Click()
Range("B7") = ExDeciToBin(170)
End Sub
|
|