I am calculating XOR
of two short integers
using XOR ^
operator in a traditional fashion. Below is the method-
short a=197;
short b=341;
short y = (short) (a ^ b);
However the XOR always returned integer but in my case inputs are short integer, that is why i am casting short to the XOR output. The XOR can be calculated in different manners (example: using BigInteger
etc.) but performance wise (less time) which is the best for short integers? While keeping performance in mind, should i first convert each short integer to binary number using Integer.toBinaryString(number)
then apply bitwise XOR?
XOR on the same argument: x ^ x = 0 If the two arguments are the same, the result is always 0 .
In simple words, the XOR of two decimal means, first converting the two decimals to binary and then performing the bit-wise XOR and then again converting the result to decimal.
XOR Background As we can see, if both bits are similar, then the XOR equals to zero. Otherwise, the result equals to one. Put differently, the bitwise XOR operation equals zero in case the number of ones is even and equals one in case the number of ones is odd.
short s1 = ...
short s2 = ...
short result = (short) (s1 ^ s2);
This is the most efficient way to XOR two short
s together. It does not run into the overhead of creating BigInteger
s and the cast will never cause an overflow issue as both s1
and s2
are short
s to begin with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With