Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Opposite of OR

Status
Not open for further replies.

AndyGroom

Programmer
May 23, 2001
972
GB
My mind has gone blank! Setting bits is easy:
Code:
a& = a& or 64
will set bit 7 of a& to 1 regardless of the other bits and regardless of whether it's already 1 or 0.

What's the opposite of that code? Ie, to set bit 7 to 0 without changing any of the other bits and regardless of whether it's already 0 or 1?

- Andy
___________________________________________________________________
If you think nobody cares you're alive, try missing a couple of mortgage payments
 
The standard way to set a bit is to [tt]Or[/tt] it with the required bitmask. To reset a bit, [tt]And[/tt] it with the 1's complement of the same bitmask. The 1's complement is obtained using the [tt]Not[/tt] operator.
See the following example.
___
[tt]
Private Sub Form_Load()
Dim X As Byte
X = 50 '=110010b

'turn on bit #7
SetBit X, 7
MsgBox X '178=10110010b

'turn off bit #7
ResetBit X, 7
MsgBox X '50=110010b
End
End Sub

Sub SetBit(Number, Bit)
Number = Number Or (2 ^ Bit)
End Sub

Sub ResetBit(Number, Bit)
Number = Number And Not (2 ^ Bit)
End Sub[/tt]
___

Note that in above functions, the Bit argument is counted from 0 instead of 1 which is more conventional. Thus LSB in a byte corresponds to Bit #0 and MSB corresponds to Bit #7.

See also thread222-1158422 in which I am doing the same thing for setting/resetting bits in a long integer.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top