+ 2
xor in java
can someone give me an example of a method to calculate xor WITHOUT using the ^ operator in java?
2 Answers
+ 1
In Boolean conditionals (A XOR B) is the same logic as
(A != B)
In bitwise operations an equivalent implementation to (a ^ b) is
((a & ~b) | (~a & b))
+ 1
// pseudo code: should works...
char bxor(char x, char y) {
return y=='0' ? x : x=='0' ? y : '0';
}
int xor(int a, int b) {
// convert to binary strings
a = str(a,2);
b = str(b,2);
// zero left-pad
int n = max(length(a),length(b));
a = '0'.repeat(n)+a).slice(-n);
b = '0'.repeat(n)+b).slice(-n);
// iterate and xor digit after digit
int i, r = '';
for (i=0; i<length(a); ++i) r += bxor(a[i],b[i]);
// return integer from base 2
return parseInt(r,2);
}