XOR of two short integers

后端 未结 3 1983
醉酒成梦
醉酒成梦 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:32

    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.

提交回复
热议问题