我想添加两个short,就好像它们是无符号的,并从加法中获得进位。
因此,例如,以下以二进制
表示的短裤1111111111111111 (-1) +
0000000000000001 (1)
----------------
0000000000000000 (0)
它们的加法具有1
的进位
是否有办法从2的互补加法中获得这个进位?
任何解决方案的唯一限制是不能使用以下数据类型:int, long, char,因为我在Java Card平台上工作
更新:
我需要这个的原因是用两个短裤重新创建整数加法。我正在使用Java Card平台,它不支持整数,因此我想用两个short来表示一个整数。
WJS的答案是完美的,我需要的。下面的代码块演示了我想要创建的内容:
short xA = (short) 0b1111111111111111, xB = (short) 0b1111111111111111;
short yA = (short) 0b0000000000000000, yB = (short) 0b0000000000000001;
short targetA, targetB;
targetA = (short) (xA + yA + (xB < 0 && yB < 0 || xB < 0 && yB >= -xB || yB < 0 && xB >= -yB ? 1 : 0));
targetB = (short) (xB + yB);
其中A
为整数的高部,B
为整数的低部。
这个代码块是target = x + y
的缩写。
您可以这样做。
- a和b均为负
- a为负值,b>= -a
- b为负值,a>= -b
short a = some short;
short b = some short;
short carry = getCarry(a, b);
public static short getCarry(short a, short b) {
if (a < 0 && b < 0 || a < 0 && b >= -a || b < 0 && a >= -b) {
return 1;
}
return 0;
}
我通过比较这个进位和在添加两个short后级联到整数的上16位的进位来测试这一点。在所有情况下,两个进位是相等的。
你只需将相加的结果与原始数字进行比较。
public static void main(String[] args) {
short a = -1;
short b = 1;
short sum = (short)(a + b);
int carry = Short.compareUnsigned(sum, a) < 0 ? 1 : 0;
System.out.printf("sum = %d carry = %d%n", sum, carry);
}
输出:
sum = 0 carry = 1
如果您没有Short.compareUnsigned()
,您可以使用以下替代方案。参见计算进位标志-堆栈溢出
static boolean unsignedLessThan(short a, short b) {
return (a ^ Short.MIN_VALUE) < (b ^ Short.MIN_VALUE);
}