XOR of two short integers

Ravi Joshi picture Ravi Joshi · Mar 24, 2012 · Viewed 35k times · Source

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?

Answer

Jeffrey picture Jeffrey · Mar 24, 2012
short s1 = ...
short s2 = ...
short result = (short) (s1 ^ s2);

This is the most efficient way to XOR two shorts together. It does not run into the overhead of creating BigIntegers and the cast will never cause an overflow issue as both s1 and s2 are shorts to begin with.