Search code examples
javajavacard

How to get the value of the carry bit when adding two shorts in Java


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.


Solution

  • You can do it like this. A carry will occur if.

    • a and b are both negative
    • a is negative and b >= -a
    • b is negative and 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;
    }
    
    

    I tested this by comparing this carry to the one that would cascade into the upper 16 bits of an integer after addition of two shorts. In all cases, the two carry bits were equal.