xor in java | Sololearn: Learn to code for FREE!
+ 2

xor in java

can someone give me an example of a method to calculate xor WITHOUT using the ^ operator in java?

1st Feb 2021, 4:38 PM
Yousef Ady
Yousef Ady - avatar
2 ответов
+ 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))
1st Feb 2021, 9:23 PM
Brian
Brian - avatar
+ 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); }
1st Feb 2021, 5:03 PM
visph
visph - avatar