Need help with XNOR operation

# Thread: Need help with XNOR operation

1. Member
Join Date
Dec 1969
Posts
75

## Need help with XNOR operation

Hi all, <BR>I&#039;m trying to implement an XNOR operation in SQL Server. This is what i have:<BR><BR>===================================== ===========<BR>CREATE PROCEDURE test_xnor AS<BR>declare<BR> @x smallint,<BR> @y smallint,<BR> @z smallint<BR><BR>set @x = 12 -- 1100<BR>set @y = 10 -- 1010<BR><BR><BR>select @z = (@y & @x) &#124 (~@x & ~@y)<BR>select @z as z, @x as x, @y as y<BR>GO<BR>======================================= =========<BR><BR>the value of @z should be 9 (1001)but I&#039;m getting -7 instead. Anyone have any idea?

2. Senior Member
Join Date
Dec 1969
Posts
96,118

You are ignoring all the bits *above* the 8 bit in seeing only the answer of 9.<BR><BR>Here&#039;s how it actually happens:<BR><BR>x = 00001100<BR>y = 00001010<BR><BR>x & y = 00001000<BR><BR>~x = 11110011<BR>~y = 11110101<BR>~x & ~y = 11110001<BR><BR>(x & y) &#124 (~x & ~y) = 11111001<BR><BR>NOW...if you chop off the upper 1 bits, so you only have 4 bits left, yes you get the answer of 9.<BR><BR>But as you asked for it, you correctly get -7.<BR><BR>******************<BR><BR>Incidentally, why do<BR><BR> select @z = (@y & @x) &#124 (~@x & ~@y)<BR><BR>When you could more easily do<BR> <BR> select @z = ~ ( @x ^ @y )<BR><BR>After all, "XNOR" really simply means "NOT XOR".<BR><BR>Try it.<BR><BR>Anyway, if you only want an answer with 4 bits, then mask the result to only 4 bits:<BR><BR> select @z = ( ~ ( @x ^ @y ) ) & 15<BR><BR><BR>

3. Senior Member
Join Date
Dec 1969
Posts
96,118

## And yes I know...

...that I showed TINYINT values there instead of SMALLINT, but it&#039;s the same thing for SMALLINT except with 16 bits instead of only 8. <BR><BR>

4. Member
Join Date
Dec 1969
Posts
75

## RE: That's the right answer...

Thanks Bill,<BR>you always have the answer don&#039;t you :-)<BR><BR>have a wonderful friday and thanks again for the help.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•