T-SQL XOR Operator - sql-server

Is there an XOR operator or equivalent function in SQL Server (T-SQL)?

There is a bitwise XOR operator - the caret (^), i.e. for:
SELECT 170 ^ 75
The result is 225.
For logical XOR, use the ANY keyword and NOT ALL, i.e.
WHERE 5 > ANY (SELECT foo) AND NOT (5 > ALL (SELECT foo))

Using boolean algebra, it is easy to show that:
A xor B = (not A and B) or (A and not B)
A B | f = notA and B | g = A and notB | f or g | A xor B
----+----------------+----------------+--------+--------
0 0 | 0 | 0 | 0 | 0
0 1 | 1 | 0 | 1 | 1
1 0 | 0 | 1 | 1 | 1
1 1 | 0 | 0 | 0 | 0

As clarified in your comment, Spacemoses, you stated an example: WHERE (Note is null) ^ (ID is null). I do not see why you chose to accept any answer given here as answering that. If i needed an xor for that, i think i'd have to use the AND/OR equivalent logic:
WHERE (Note is null and ID is not null) OR (Note is not null and ID is null)
That is equivalent to:
WHERE (Note is null) XOR (ID is null)
when 'XOR' is not available.

MS SQL only short form (since SQL Server 2012):
1=iif( a=b ,1,0)^iif( c=d ,1,0)

The xor operator is ^
For example: SELECT A ^ B where A and B are integer category data types.

It is ^ http://msdn.microsoft.com/en-us/library/ms190277.aspx
See also some code here in the middle of the page How to flip a bit in SQL Server by using the Bitwise NOT operator

<> is generally a good replacement for XOR wherever it can apply to booleans.

From your comment:
Example: WHERE (Note is null) ^ (ID is null)
you could probably try:
where
(case when Note is null then 1 else 0 end)
<>(case when ID is null then 1 else 0 end)

Related

Bitwise AND with 0 is unreachable in C

I want to check if the LSB is 0.
if(some_size_t & 1){} works fine
But why is if(some_size_t & 0){//This parts is unreachable} never reachable?
Because in order to ever get the value 1 i.e. true both operands for the logical and bitwise & i.e. AND operator have to be 1. Its so called truth table is
op1 | op2 | op1 AND op2
=====================
0 | 0 | 0
1 | 0 | 0
0 | 1 | 0
1 | 1 | 1
Because your value, e.g. op2, 0 has only zeros, no ones, you will always get only zeros as a result, no matter the other operand. And 0 will evaluate to false. It's what we call a contradiction in logic, often noted with a up side down T or \bot in latex.
As then the if condition is always false, the code in its body will never be executed, i.e. is unreachable.

Using Bitwise Operators in C [duplicate]

This question already has answers here:
How does this work? Weird Towers of Hanoi Solution
(3 answers)
Closed 3 years ago.
I am a beginner to C language.I have a code for towers of hanoi but can someone explain me what are these bitwise operators doing ie if value of i is 1 what will be the source and target output value ?
source = (i & i-1) % 3;
target = ((i | i-1) + 1) % 3;
i & i-1 turns off the lowest set bit in i (if there are any set). For example, consider i=200:
200 in binary is 1100 1000. (The space is inserted for visual convenience.)
To subtract one, the zeros cause us to “borrow” from the next position until we reach a one, producing 1100 0111. Note that, working from the right, all the zeros became ones, and the first one became a zero.
The & produces the bits that are set in both operands. Since i-1 changed all the bits up to the first one, those bits are clear in the &—none of the changed bits are the same in both i and i-1, so none of them is a one in both. The other ones in i, above the lowest one bit, are the same in both i and i-1, so they remain ones in i & i-1. The result of i & i-1 is 1100 0000.
1100 0000 is 1100 1000 with the lowest set bit turned off.
Then the % 3 is selecting which pole in Towers of Hanoi to use as the source. This is discussed in this question.
Similarly i | i-1 turns on all the low zeros in i, all the zeros up to the lowest one bit. Then (i | i-1) + 1 adds one to that. The result is the same as adding one to the lowest one bit in i. That is, the result is i + x, where x is the lowest bit set in i. Using our example value:
i is 1100 1000 and i-1 is 1100 0111.
i | i-1 is 1100 1111.
(i | i-1) + 1 is 1101 0000, which equals 1100 1000 + 0000 1000.
And again, the % 3 selects a pole.
A quick overview of bitwise operators:
Each operator takes the bits of both numbers and applies the operation to each bit of it.
& Bitwise AND
True only if both bits are true.
Truth table:
A | B | A & B
-------------
0 | 0 | 0
1 | 0 | 0
0 | 1 | 0
1 | 1 | 1
| Bitwise OR
True if either bit is true.
Truth table:
A | B | A | B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 1
^ Bitwise XOR
True if only one bit is true.
Truth table:
A | B | A ^ B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 0
~ Bitwise NOT
Inverts each bit. 1 -> 0, 0 -> 1. This is a unary operator.
Truth table:
A | ~A
------
0 | 1
1 | 0
In your case, if i = 1,
the expressions would be evaluated as:
source = (1 & 1-1) % 3;
target = ((1 | 1-1) + 1) % 3;
// =>
source = (1 & 0) % 3;
target = ((1 | 0) + 1) % 3;
// =>
source = 0 % 3;
target = (1 + 1) % 3;
// =>
source = 0;
target = 2 % 3;
// =>
source = 0;
target = 2;
Good answer above, here is a high-level approach:
i == 1:
source: (1 & 0). Are both of these values true or >= 1? No they are not. So the overall result is 0, 0 % 3 = 0.
target: ((1 | 0) + 1) % 3.
(1 | 0) evaluates to 1(true) since one of the two values on the sides of the | operator are 1, so now we have (1 + 1). so then it follows we have 2 % 3 = 2.
Source: 0, target: 2

what is the function of $value & 15

I have been going over a perl book i have recently purchased, and while reading I noticed a block of code that confused me..
use integer;
$value = 257;
while($value){
unshift #digits, (0..9,a..f)[$value & 15];
$value /= 16;
}
print digits;
the book mentions the purpose was to reverse the order of digits. however, new to perl I am having trouble figuring out what [$value & 15] is doing.
It's a bitwise and operation.
What it's doing is performing a bitwise and using the value of 15 and whatever value is contained in $value.
The resulting value is the decimal value that corresponds to the result of a bitwise and with the lower 4 bits of the value.
Ex:
$value = 21
which has a binary representation of: 0b10101
Performing a bitwise and with 15 means that any bits in $value will be zeroed if they are either outside the lower 4 bit range, or contain no 1's in the lower 4 bits.
The result is:
0b10101
&
0b 1111
-------
0b00101 = 5
Looking up the truth tables for performing bitwise operations will help with stuff like this in the future, but when performing an AND with any value, the result is only true, when both bits are 1, 0 otherwise.
V1 | V2 | V1 & V2
-----------------
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

C Programming - XOR Bitwise Operation

What operation does the following ‘C’ statement perform?
star = star ^ 0b00100100;
(A) Toggles bits 2 and 5 of the variable star.
(B) Clears all bits except bits 2 and 5 of the variable star.
(C) Sets all bits except bits 2 and 5 of the variable star.
(D) Multiplies value in the variable star with 0b00100100.
I'm still clueless about this. Can someone help me out?
XOR operator (also called "logical addition") is defined like this:
a b a^b
-----------
0 0 0
0 1 1
1 0 1
1 1 0
So a^0 leaves a intact while a^1 toggles it.
For multiple-bit values, the operation is performed bitwise, i.e. between corresponding bits of the operands.
If you know how XOR works, and you know that ^ is XOR in C, then this should be pretty simple. You should know that XOR will flip bits where 1 is set, bits 2 and 5 of 0b00100100 are set, therefore it will flip those bits.
From an "during the test" standpoint, let's say you need to prove this to yourself, you really don't need to know the initial value of star to answer the question, If you know how ^ works then just throw anything in there:
00100100
^10101010 (star's made up value)
---------
10001110 (star's new value)
bit position: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0
|---|---|---|---|---|---|---|---
star's new v: | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0
|---|---|---|---|---|---|---|---
star's old v: | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0
Then check your answers again, did it:
(A) Toggles bits 2 and 5 of the variable star. (Yes)
(B) Clears all bits except bits 2 and 5 of the variable star. (Nope)
(C) Sets all bits except bits 2 and 5 of the variable star. (Nope)
(D) Multiplies value in the variable star with 0b00100100. (36x170 = 142? Nope)
It is (A) toggles bits 2 and 5.
The following is the truth table for the XOR operation:
x y x^y
0 0 0
1 0 1
0 1 1
1 1 0
You can see from the table that x XOR 0 = x and x XOR 1 = !x.
XOR is a bitwise operation, so it operates on individual bits. Therefore if you XOR star with some constant, it will toggle the 1 bits in the constant.
You can find some explanation e.g. here.
The exclusive OR has this truth table:
A B A^B
-----------
1 1 0
1 0 1
0 1 1
0 0 0
We can see that if B is true (1) then A is flipped (toggled), and if it's false (0) A is left alone. So the answer is (A).
XOR operator returns 0 if both inputs are same otherwise returns 1 if both inputs are different.For Example the Given Truth Table :-
a=1 b=1 => a^b=0,
a=0 b=0 => a^b=0,
a=0 b=1 => a^b=1,
a=1 b=0 => a^b=1.
well xor is binary operator that work on bits of 2 nos.
rule of xoring:for same bit ans is 0 and for different bit ans is 1
let
a= 1 0 1 0 1 1
b= 0 1 1 0 1 0
--------------
c= 1 1 0 0 0 1
--------------
compare bit of a and b bit by bit
if same put 0 else put 1
xor is basically used to find the unique in given set of duplicate no.
just xor all nos. and u will get the unique one(if only single unique is present)

4-variable mapping into an array

I need to choose an aray item based on the values of 4 variables, as shown below, in C.
0 | 1 | 0 | -1 | array[1][0]
-1 | 0 | 1 | 0 | array[1][1]
0 | -1 | 0 | 1 | array[1][2]
1 | 0 | -1 | 0 | array[1][3]
1 | 0 | 0 | -1 | array[2][0]
1 | 0 | 0 | 1 | array[2][1]
-1 | 0 | 0 | 1 | array[2][2]
-1 | 0 | 0 | -1 | array[2][3]
0 | 1 | -1 | 0 | array[3][0]
0 | 1 | 1 | 0 | array[3][1]
0 | -1 | 1 | 0 | array[3][2]
0 | -1 | -1 | 0 | array[3][3]
(The order of the second column in the array isn't important and can be reordered if needed.)
While it's possible (and completely acceptable) to just stick all the possibilities in 12 chained ifs, I'd like to see if anyone can come up with a "cleaner" solution.
EDIT: to clarify: I want a function f(a,b,c,d) where (for example) f(0, 1, 0, -1) returns the value held in array[1][0].
I've described this solution in a way which is slightly less efficient than it could be to make it easier to explain; the more concise version is easily derived from what I have shown here.
Map the values -1, 0, and 1 to 0x00, 0x01, and 0x02, and store them, using 2 bits per value, in an 8-bit value so e.g. your array values correspond to the following numbers:
array[1][0]: binary value 01100100 = 0x64
array[1][1]: binary value 00011001 = 0x19
array[1][2]: binary value 01000110 = 0x46
array[1][3]: binary value 10010001 = 0x91
Create an array for all 255 possible values which can be held in an 8-bit value (note that some entries won't be used, i.e. any with both bits set to 1 - this is the inefficiency I mentioned).
So e.g.
array[0] points to the appropriate array for -1, -1, -1, -1
array[1] points to the appropriate array for -1, -1, -1, 0
array[2] points to the appropriate array for -1, -1, -1, 1
array[3] points nowhere
array[4] points to the appropriate array for -1, -1, 0, -1
array[5] points to the appropriate array for -1, -1, 0, 0
array[6] points to the appropriate array for -1, -1, 0, 1
array[7] points nowhere
(etc, obviously)
And then all you need is a single lookup, with no loop, to get the right array (or whatever you are keying to).
In the more concise solution, the table has no entries pointing to nowhere.
EDIT:
In this case, with array as above, the desired function is:
f(a,b,c,d) {
return array[(a+1) << 6 + (b+1) << 4 + (c+1) << 2 + (d+1)];
}
Revise your way of thinking and recognise that an array IS a function, from a set of indices to a set of values. Looked at this way, you would want to define your array like this:
array[0][1][0][-1] = value currently in array[1][0]
array[-1][0][1][0] = value currently in array[1][1]
etc
Now, it's unfortunate that C can't directly index arrays with arbitrary ranges of integers, but you could get round this in one of two ways:
defining constants such as one=1,zero=0,minusone=2 and use those in your array expressions;
use an offset such as adding 1 to every index and subtracting it when you make a reference to the array, eg array[1-1][2-1][1-1][0-1].
Of these two the former is probably preferable.
Finally, this array will have entries for values not in your table, you'll have to put some sort of null code into them.
Put the table you posted in array and search in it with a loop for the correct entry. This way you will code data as data and not as code.
Any cleverer method will generate undue maintenance work once your mapping specification changes. Unless the performance of the loop is proven to be unsufficient I would use the loop.
In addition to approaches suggested by #James McLeod and #High Performance Mark you could use the auto-generated switch statement:
f(a,b,c,d) {
switch(ind(a,b,c,d)) {
# include "cases.h"
default: assert(0);
};
}
Where ind():
enum { BASE = 3 };
int ind(int a, int b, int c, int d) {
// ind() should produce the same result as the one from the script (see below)
return (BASE*(BASE*(BASE*(a+1) + b+1) + c+1) + d+1);
}
And cases.h:
case 48: return array[1][0];
case 16: return array[1][1];
case 32: return array[1][2];
case 64: return array[1][3];
case 66: return array[2][0];
case 68: return array[2][1];
case 14: return array[2][2];
case 12: return array[2][3];
case 46: return array[3][0];
case 52: return array[3][1];
case 34: return array[3][2];
case 28: return array[3][3];
cases.h could be generated by the following script:
#!/usr/bin/env python
import csv, fileinput
# parse stdin or file(s) given at command-line as csv-file
rows = ((map(int, row[:-1]), row[-1])
for row in csv.reader(fileinput.input(), delimiter='|') if row)
# function that arranges indexes in C-order
# . any function that produces unique integers will do
# . -1 <= n <= 1
ind = lambda args, base=3: reduce(lambda acc, n: base*acc + (n+1), args, 0)
# print cases for switch(ind(a,b,c,d)) statement
print '\n'.join("case %d: return %s;" % (ind(indexes), value)
for indexes, value in rows if value)
The script accepts as an input the table from your question.

Resources