Reputation: 6328
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?
Upvotes: 9
Views: 36606
Reputation: 150108
I'm not 100% sure what you're asking, but hopefully this helps:
Java coerces both operands to type int. That is why the result is an int.
so your shorts will be automatically converted to an int, and the XOR operation will be done very efficiently on the integer operands.
If one of the operands is a long, both types are instead coerced to a long. However, that does not apply in your case.
Bottom line, given that both of your inputs are short, if you need a short result, the most efficient thing to do is
short result = (short) (operandA ^ operandB);
Upvotes: 1
Reputation: 44808
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.
Upvotes: 10
Reputation: 1500065
It's not really clear what you mean by "convert each short integer to binary number" - a short is already a number, and its representation is naturally binary anyway.
You just want:
short x = ...;
short y = ...;
short z = (short) (x ^ y);
You need the cast as x ^ y
will promote both to int
, and the result will be an int
. However, the result will have to be in the range of a short
anyway, so it's safe to perform this cast without losing information.
See section 15.22.1 of the JLS for more information about XOR in particular and section 5.6.2 for information on binary numeric promotion in general.
Upvotes: 5