3

I can't understand the usage of & operator in following queries:

select Flags & 1 from tFlags where Flags = 524675
output: 1

select Flags & 1 from tFlags where Flags = 525698
output: 0

I know that it is bitwise operator. I don't understand how can someone who writes the query should know whether it is 0 or 1 or anything else. And why it equals 0 or 1

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
rakamakafo
  • 1,144
  • 5
  • 21
  • 44
  • Possible duplicate of [Comparing two bitmasks in SQL to see if any of the bits match](http://stackoverflow.com/questions/143712/comparing-two-bitmasks-in-sql-to-see-if-any-of-the-bits-match) – Alex K. Oct 12 '15 at 11:17

1 Answers1

3

& is bitwise AND (only 1 & 1 => 1):

LiveDemo

CREATE TABLE #tFlags(Flags INT);

INSERT INTO #tFlags VALUES (524675), (525698);

select *
       ,[bitwise AND] = CONCAT(Flags, '& 1 = ')
       ,[result]      = Flags & 1  
from #tFlags;

How it works:

000010000000000110000011   524675
000000000000000000000001   1       &
------------------------
000000000000000000000001   1

and:

000010000000010110000010   525698
000000000000000000000001   1       &
------------------------
000000000000000000000000   0   

The simple answer is:

  • odd number & 1 = 1
  • even number & 1 = 0

EDIT:

Number & 255: You can get rid of data except byte one.

00000001 00101100    300
00000000 11111111    255   &
-----------------
00000000 00101100    44

The point is you can treat binary number and bitwise operation as masking and use it to set/reset/xor value based on specific position.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • I saw the usage of this type operators many times.People just write Flags&255 or Flags&196. How they determine that this will work. I don't think that people know directly the 0,1 counterparty of number? Any ideas? – rakamakafo Oct 12 '15 at 11:23
  • @Sher This is quite easy: 1 (bit 0) + 2 (bit 1) + 4 (bit 2) + 8 (bit 3) + 16 + 32 + 64 +128 = 255. 196 = 128 + 68, 68 = 64 + 4, 4 = 4 + 0 => 11 000100 – Julien Vavasseur Oct 12 '15 at 11:58