问题描述
我正在使用 XOR ^ 短整数
的 XOR
$ c>以传统方式运营。以下是方法 -
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);
然而,XOR总是返回整数但在我的情况下输入是短整数,这就是为什么我要投XOR输出短路。 XOR可以用不同的方式计算(例如:使用 BigInteger
等),但性能明智(更少的时间),这对短整数最好?在记住性能的同时,我应该首先使用 Integer.toBinaryString(number)
将每个短整数转换为二进制数,然后应用按位XOR?
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?
推荐答案
short s1 = ...
short s2 = ...
short result = (short) (s1 ^ s2);
这是XOR两个短在一起。它不会遇到创建
BigInteger
的开销,并且转换将永远不会导致溢出问题,因为 s1
和 s2
以短
开头。
This is the most efficient way to XOR two
short
s together. It does not run into the overhead of creating BigInteger
s and the cast will never cause an overflow issue as both s1
and s2
are short
s to begin with.
这篇关于两个短整数的异或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!