Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit-flipping operations in T-SQL

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?

like image 988
Christian Dalager Avatar asked Jul 10 '09 15:07

Christian Dalager


People also ask

How do you flip a bit in SQL?

You can just flip the value of the bit field by prefixing it with ~ before it.

What is SQL Bitmask?

Bitmasking is an exercise of compiling multiple values that are normally represented in a number of data types to a single computer word. In a previous example, we used the binary data type to see how bit manipulation is represented visually.


2 Answers

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)
like image 134
David M Avatar answered Sep 20 '22 12:09

David M


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

like image 38
Charles Bretana Avatar answered Sep 22 '22 12:09

Charles Bretana