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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With