Sunday, June 15, 2008

How to check a Bit whether it is 1 or 0 (zero) in an Integer (Bitwise Operations)

Level: Beginner

Knowledge Required:
  • Bitwise Operators
  • Enum

Description:
We usually get statuses from different resources, which contains one or more statuses together. So we require to check whether a particular Status is set or NOT.

Normally statuses are set using Enum

Example:

Public Enum EnumFontStyle
Regular = 0
Bold = 1
Italic = 2
Underline = 4
StrikeThrough = 8
End Enum

Public Sub Test()
Dim fs As EnumFontStyle
fs = EnumFontStyle.Bold OR EnumFontStyle.Italic
If fs And EnumFontStyle.Bold Then
MsgBox("Font is Bold")
Else
MsgBox("Font is NOT Bold")
End If
End Sub

To understand how it is working,

Suppose we have an integer = 3 => binary = 11, if we perform,

3 AND 2

This is in binary

11 AND 10

11
AND 10
----------
10 = 2
Hence bit number 2 is 1, because if we do,
4 AND 2 (binary = 100 AND 10)

100
AND 010
----------
000 = 0
This means bit number 2 = 0

See Also:
How to add/remove Attribute from File (Bitwise Operation)
How to Make a Bit Zero in an Integer (Bitwise Operation)

No comments: