XOR of two short integers

I compute the XOR two short integers using the XOR ^ operator in the traditional way. Below is the method -

 short a=197; short b=341; short y = (short) (a ^ b); 

However, XOR always returned an integer, but in my case the input is short integers, so I lose the result of XOR. XOR can be calculated differently (example: using BigInteger , etc.), but in terms of performance (less time), what is best for short integers? With performance in mind, do I need to first convert each short integer to a binary number using Integer.toBinaryString(number) , and then apply bitwise XOR?

+6
source share
3 answers
 short s1 = ... short s2 = ... short result = (short) (s1 ^ s2); 

This is the most efficient way to XOR two short together. This does not lead to the overhead of creating a BigInteger , and casting does not cause an overflow problem, since s1 and s2 are short for starters.

+8
source

It's not entirely clear what you mean by "convert every short integer to binary" - short is already a number, and its representation, of course, is binary.

You just want to:

 short x = ...; short y = ...; short z = (short) (x ^ y); 

You need cast because x ^ y will support both int and the result will be int . However, in any case, the result should be in the short range, so it is safe to perform this cast without loss of information.

See JLS Section 15.22.1 for more information on XOR in particular, and Section 5.6.2 for information on binary digital advertising in general.

+4
source

I am not 100% sure what you are asking, but hopefully this helps:

Java forces both operands to int. That is why the result is int.

http://java.comsci.us/syntax/expression/bitwisexor.html

therefore, your shorts will be automatically converted to int, and the XOR operation will be performed very efficiently on integer operands.

If one of the operands is long, both types are instead forced to length. However, this does not apply to your case.

On the bottom line, given that both of your entries are short, if you need a short result, the most efficient thing is

 short result = (short) (operandA ^ operandB); 
+1
source

Source: https://habr.com/ru/post/911582/


All Articles