I want to add two shorts as if they are unsigned and get the carry bit from the addition.
So for example, the following shorts represented in binary
1111111111111111 (-1) +
0000000000000001 (1)
----------------
0000000000000000 (0)
Their addition has the carry bit of 1
.
Is there a way to obtain this carry bit from two's compliment addition?
The only restriction to any solution is that the following data types cannot be used: int, long, char because I'm working on the Java Card platform
UPDATE:
The reason I need this is to re-create integer addition with two shorts. I am working with the Java Card platform, which doesn't support integers, hence I wanted to use two shorts to represent one integer.
WJS's answer was perfect for what I needed. The following code block illustrates what I wanted to create:
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);
Where A
is the high part and B
is the low part of the integer.
This code block is the short equivalent of target = x + y
.