Bitwise operations in TSQL Take the following code:

Declare @a integer
set @a = 0
set @a = @a | cast (1 as BINARy)
set @a = @a | cast (100 as BINARy)
select cast (@a as integer)


Now, shouldn't the output of this code be 5 ?

I have an integer, set it to 0, so in binary its all 0's

then I OR it with 1 , so it becomes 0..001

then I OR it with 100 in binary, so it should become 00..0101 which, in decimal is 5

The output I actually get is 101

EDIT: for more clarity, I'm trying to accomplish with TSQL what the following code does in C++

#include&lt;stdio.h&gt;
#include&lt;iostream&gt;
using namespace std;
int main()
{
int a;
a = 0;
a = a | 1;
cout&lt;&lt; a;
a = a | 0b100;
cout&lt;&lt;endl&lt;&lt;a;
}
Your cast isn't doing what you think it should.

select cast(cast(100 as binary) as int) equals 100.  In other words, you are casting the decimal value 100 to binary, not taking '100' in base-2 notation.

Your expectation is actually this:

Declare @a integer
set @a = 0
set @a = @a | cast (1 as BINARY)
set @a = @a | cast (5 as BINARY)
select cast (@a as integer)


Incidentally, if this is new development, I very highly recommend against bit shifting in SQL Server.  It's slow, difficult to maintain, and violates first normal form.  If it's not, I'll guess that you probably know this already...

To convert binary to decimal, you can create a function.  There are other ways of going from integer to display base-2 notation, but this feels like it would be quite slow.