VB中如何判断一个32位的Integer其中的某一位,比如第10位是0还是1(二进制值)?

2024-12-27 21:24:09
推荐回答(3个)
回答1:

vb 逻辑远算符也是位运算运算符 

Private Function IsBitSetNotZero(x As Long, n As Integer) As Integer

    If n < 1 Or n > 32 Then

        IsBitSetNotZero = -1 '返回-1表示传入参数错误,1表示该位为1,0表示该位为零

    Else

        If n <= 31 Then

            Dim d As Long

            d = 2 ^ (n - 1)

            If (x And d) = d Then

                IsBitSetNotZero = 1

            Else

                IsBitSetNotZero = 0

            End If

        Else

            If (x And &H80000000) = &H80000000 Then

                IsBitSetNotZero = 1

            Else

                IsBitSetNotZero = 0

            End If

        End If

    End If

End Function


Private Sub comm_sub(a As Long, i As Integer, ret As Integer)

    If ret < 0 Then

        MsgBox "传入参数错误"

    Else

        If ret > 0 Then

            MsgBox "a = " & Hex(a) & " 的第" & CStr(i) & " 位为1"

        Else

            MsgBox "a = " & Hex(a) & " 的第" & CStr(i) & " 位为0"

        End If

    End If

End Sub


Private Sub Command1_Click()

    Dim a As Long

    Dim i As Integer

    Dim ret As Integer

    a = &H80000003

    i = 0

    ret = IsBitSetNotZero(a, i)

    comm_sub a, i, ret

End Sub


Private Sub Command2_Click()

    Dim a As Long

    Dim i As Integer

    Dim ret As Integer

    a = &H80000003

    i = 1

    ret = IsBitSetNotZero(a, i)

    comm_sub a, i, ret

End Sub


Private Sub Command3_Click()

    Dim a As Long

    Dim i As Integer

    Dim ret As Integer

    a = &H80000003

    i = 32

    ret = IsBitSetNotZero(a, i)

    comm_sub a, i, ret

End Sub


Private Sub Command4_Click()

    Dim a As Long

    Dim i As Integer

    Dim ret As Integer

    a = &H80000003

    i = 3

    ret = IsBitSetNotZero(a, i)

    comm_sub a, i, ret

End Sub


Private Sub Command5_Click()

    Dim a As Long

    Dim i As Integer

    Dim s As String

    a = &H80750003

    s = ""

    For i = 1 To 32

        s = s & "a = 0x" & Hex(a) & " 的第" & CStr(i) & "位为" & CStr(IsBitSetNotZero(a, i)) & vbCrLf

        If i < 32 And i Mod 8 = 0 Then s = s & "  ==========  " & vbCrLf

    Next

    MsgBox s

End Sub

回答2:

mid函数就可以了

newstring = Mid(字符串,截取开始位置,截取个数)

截取开始位置=len(字符串)-第几位+1

截取个数=1

回答3:

我写了一个,你看是不是这样的?