How to Perform Bit Manipulation In Visual BasicID: Q113476
|
Visual Basic does not explicitly support the Set, Clear, Toggle, and Examine bit manipulation functions. This article describes how to simulate these functions in Visual Basic.
Bit-level manipulation is common practice for operating systems and
programs that need to conserve space. Eight Yes/No, On/Off bits of data may
be stored in a single byte rather than using up 8 bytes. Visual Basic can't
address the bit level directly, but by using logical operators, it can
manipulate bit data by working with one byte at a time.
Sub Command1_Click ()
' The following clears the high-order byte & returns only the
' low order byte:
Byte% = Text1.Text And &HFF
Bit% = Text2.Text
If Bit% <= 7 Then
Label1.Caption = "The original value of the Byte is " & Byte%
Temp% = ExamineBit(Byte%, Bit%)
Enter the following two lines as one, single line of code:
Label2.Caption =
"Bit " & Bit% & IIf(Temp%, " is ", " is not ") & "set"
Call ClearBit(Byte%, Bit%)
Enter the following two lines as one, single line of code:
Label3.Caption =
"The value with bit " & Bit% & " clear is " & Str$(Byte%)
Call SetBit(Byte%, Bit%)
Label4.Caption = "The value with bit " & Bit% & " set is " & Byte%
Call ToggleBit(Byte%, Bit%)
Enter the following two lines as one, single line of code:
Label5.Caption =
"The value after toggling bit " & Bit% & " is " & Byte%
Else
MsgBox ("Please enter a value less than 8 in the Bit TextBox.")
End If
End Sub
' The ClearBit Sub clears the nth bit (Bit%) of an integer (Byte%).
Sub ClearBit (Byte%, Bit%)
' Create a bitmask with the 2 to the nth power bit set:
Mask% = 2 ^ Bit%
' Clear the nth Bit:
Byte% = Byte% And Not Mask%
End Sub
' The ExamineBit function will return True or False depending on
' the value of the nth bit (Bit%) of an integer (Byte%).
Function ExamineBit% (Byte%, Bit%)
' Create a bitmask with the 2 to the nth power bit set:
Mask% = 2 ^ Bit%
' Return the truth state of the 2 to the nth power bit:
ExamineBit% = ((Byte% And Mask%) > 0)
End Function
' The SetBit Sub will set the nth bit (Bit%) of an integer (Byte%).
Sub SetBit (Byte%, Bit%)
' Create a bitmask with the 2 to the nth power bit set:
Mask% = 2 ^ Bit%
' Set the nth Bit:
Byte% = Byte% Or Mask%
End Sub
' The ToggleBit Sub will change the state of the nth bit (Bit%)
' of an integer (Byte%).
Sub ToggleBit (Byte%, Bit%)
' Create a bitmask with the 2 to the nth power bit set:
Mask% = 2 ^ Bit%
' Toggle the nth Bit:
Byte% = Byte% Xor Mask%
End Sub
Additional query words: 1.00 2.00 3.00
Keywords :
Version :
Platform :
Issue type :
Last Reviewed: June 25, 1999