Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XOR of two short integers

Tags:

java

xor

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?

like image 442
Ravi Joshi Avatar asked Mar 24 '12 22:03

Ravi Joshi


People also ask

What is XOR of two same numbers?

XOR on the same argument: x ^ x = 0 If the two arguments are the same, the result is always 0 .

How do you find the XOR of two decimal numbers?

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.

Can XOR two numbers be zero?

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.


1 Answers

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.

like image 198
Jeffrey Avatar answered Nov 15 '22 16:11

Jeffrey