第二种方法: 比如153转换成二进制是10011001 如果你bitvalue(153,1) 153的第一位就是1 第二位就是0,除了0就是1 Public Function BitValue(MyNumber As Long, BitNumber As Long) As Integer Dim intValue1 As Long Dim intValue2 As Long Dim intValue3 As Integer Dim intValue4 As Long Dim intValue5 As Long
If (MyNumber > 65535 Or MyNumber < 0) Then MsgBox "FUNCTION BITVALUE ERROR, OUT OF RANGE1.", vbCritical + vbOKOnly, "ERROR" Exit Function End If If (BitNumber > 16 Or BitNumber <= 0) Then MsgBox "FUNCTION BITVALUE ERROR, OUT OF RANGE2.", vbCritical + vbOKOnly, "ERROR" Exit Function End If If BitNumber = 1 Then intValue1 = MyNumber Mod 2 If intValue1 > 0.5 Then intValue3 = 1 Else intValue3 = 0 End If Else intValue1 = 2 ^ BitNumber intValue2 = MyNumber Mod intValue1 intValue4 = 2 ^ (BitNumber - 1) intValue5 = MyNumber Mod intValue4 intValue1 = intValue2 - intValue5 If intValue1 > 0.5 Then intValue3 = 1 Else intValue3 = 0 End If End If BitValue = intValue3 End Function
或
Public Function bit(DecimalValue As Long, bitN As Integer) As Boolean Dim result As String Dim ExtraDigitsNeeded As Integer DecimalValue = Abs(DecimalValue) Do result = CStr(DecimalValue Mod 2) & result DecimalValue = DecimalValue \ 2 Loop While DecimalValue > 0 '保留16位长度 ExtraDigitsNeeded = 16 - Len(result) If ExtraDigitsNeeded > 0 Then result = String(ExtraDigitsNeeded, "0") & result End If '取第几bit result = Mid(result, Abs(bitN - 16), 1) '返回数据 bit = result End Function