xlvba check if bit is set in 32-bit long integer code example
Example 1: excel vba is bit set long
'Extremely fast VBA function to test if a specified bit is set
'within a 32-bit Long integer.
'Bits are numbered from 0 to 31, so the first (least significant) bit
'is bit 0.
'Note: we do not inspect bit 31, the sign bit.
'Note: any number of bits can be specified in one call.
Function LongBitIsSet(theLong&, bit As Byte) As Boolean
Static i&, b&()
If (Not Not b) = 0 Then
ReDim b(0 To 30)
For i = 0 To 30
b(i) = 2 ^ i
Next
End If
If bit < 31 Then LongBitIsSet = theLong And b(bit)
End Function
'------------------------------------------------------------------
MsgBox LongBitIsSet(255, 7) '<--displays: True
MsgBox LongBitIsSet(230, 0) '<--displays: False
MsgBox LongBitIsSet(16384, 14) '<--displays: True
MsgBox LongBitIsSet(-16383, 0) '<--displays: True
MsgBox LongBitIsSet(&H7FFFFFFF, 0) '<--displays: True
Example 2: excel vba check if bit is set in integer
'Extremely fast VBA function to test if a specified bit is set
'within a 16-bit Integer.
'Bits are numbered from 0 to 15, so the first (least significant) bit
'is bit 0.
'Note: we do not inspect bit 15, the sign bit.
Function IntegerBitIsSet(theInteger%, bit As Byte) As Boolean
Static i&, b%()
If (Not Not b) = 0 Then
ReDim b(0 To 14)
For i = 0 To 14
b(i) = 2 ^ i
Next
End If
If bit < 15 Then IntegerBitIsSet = theInteger And b(bit)
End Function
'------------------------------------------------------------------
MsgBox IntegerBitIsSet(255, 7) '<--displays: True
MsgBox IntegerBitIsSet(230, 0) '<--displays: False
MsgBox IntegerBitIsSet(16384, 14) '<--displays: True
MsgBox IntegerBitIsSet(-16383, 0) '<--displays: True