Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you turn off a specific bit in a bit mask?

Tags:

tsql

In TSql, how do you turn off a specific bit in a bitmask without having to check to see if the bit is set or not?

like image 431
Brian Avatar asked Apr 26 '10 23:04

Brian


People also ask

How do you unset specific bits in bit patterns?

Use the bitwise AND operator (&) to clear a bit. number &= ~(1 << x); That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

How do I turn off a particular bit in a number?

The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k'th bit which is 0.

How does a bit mask work?

Bit masks are used to access specific bits in a byte of data. This is often useful as a method of iteration, for example when sending a byte of data serially out a single pin. In this example the pin needs to change its state from high to low for each bit in the byte to be transmitted.


1 Answers

Found it! Use & ~ like this...

UPDATE MyTable SET         MyBitmask = MyBitmask & ~128 -- 8th bit     WHERE MyID = 123 

The ~ operator flips all the bits (1s become 0s and 0s become 1s). Just set the value that you flip to the one you want to turn off and use & to safely turn off just the one specific bit without having to check to see if the bit is set.

like image 114
Brian Avatar answered Sep 20 '22 15:09

Brian