Bit-flipping operations in T-SQL

26,641

Solution 1

Use XOR:

SELECT value ^ 256

So in your case, SELECT 143 ^ 256 will indeed return 399. If you want to pass in the exponent as well:

SELECT value ^ POWER(2, power)

Solution 2

TSql Bitwise operators can be found here and good article on how to use them is here

Share:
26,641
Christian Dalager
Author by

Christian Dalager

Doing .Net dev from Copenhagen Denmark.

Updated on July 28, 2020

Comments

  • Christian Dalager
    Christian Dalager almost 4 years

    I have a bitmasked int field in my database. Usually I manage it through C# code, but now I need to flip a bit in the mask using T-SQL

    How do I accomplish the following:

    The bit I want to flip: 1 << 8 (256)

    The mask value before I flip: 143

    The mask value after I flip: 399

    This can be done without the bit operators that's missing in T-SQL, right?

  • Christian Dalager
    Christian Dalager almost 15 years
    thanks! It solved my problem! Is there also a way to turn on the bit in an elegant way? (i already did it, but it looks ugly...)
  • David M
    David M almost 15 years
    Are you looking to flip or turn on? Flip - use XOR (^); turn on - use OR (|). If you want more elegance, wrap in a tersely named user-defined function. :)
  • Edwin
    Edwin over 7 years
    The question is about bit shifting, the articles you posted have nothing to do with that
  • Charles Bretana
    Charles Bretana over 7 years
    The question is about bit-FLIPPING, not about bit shifting.
  • Reversed Engineer
    Reversed Engineer almost 7 years
    The title is wrongly about bit shifting, but the actual question about bit flipping.