XOR of two short integers

后端 未结 3 1935
醉酒成梦
醉酒成梦 2021-01-11 21:50

I am calculating XOR of two short integers using XOR ^ operator in a traditional fashion. Below is the method-

short a         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-11 22:41

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

提交回复
热议问题