I often see code like
int hashCode(){
return a^b;
}
Why XOR?
I often see code like
int hashCode(){
return a^b;
}
Why XOR?
Of all bit-operations XOR has the best bit shuffling properties.
This truth-table explains why:
A B AND
0 0 0
0 1 0
1 0 0
1 1 1
A B OR
0 0 0
0 1 1
1 0 1
1 1 1
A B XOR
0 0 0
0 1 1
1 0 1
1 1 0
As you can see for AND and OR do a poor job at mixing bits.
OR will on average produce 3/4 one-bits. AND on the other hand will produce on average 3/4 null-bits. Only XOR has an even one-bit vs. null-bit distribution. That makes it so valuable for hash-code generation.
Remember that for a hash-code you want to use as much information of the key as possible and get a good distribution of hash-values. If you use AND or OR you'll get numbers that are biased towards either numbers with lots of zeros or numbers with lots of ones.
XOR opertpr are reversible, i.e. suppose I have a bit string as 0 0 1
and I XOR it with another bit string 1 1 1
, the the output is
0 xor 1 = 1
0 1 = 1
1 1 = 0
now i can agan xor the 1st string with the result to get the 2nd string. i.e.
0 1 = 1
0 1 = 1
1 0 = 1
so, that makes the 2nd string a key. This behavior is not found with other bit operator
Please see this for more info --> http://stackoverflow.com/questions/1379952/why-is-xor-used-on-cryptography
XOR has the following advantages:
More info here.