XOR of two short integers

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.


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);

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.

Tags:

Java

Xor