Question

I have to use ints in java card but since the card itself does not support integers I use byte[] instead.

To represent numbers in hexadecimal format I check the first bit, if it is 1 - negative, if it is 0 - positive (binary wise). So if the leading bit is smaller than 8 it is positive, otherwise negative (hex wise).

Highest number: 7FFFFFFF

Lowest number: 80000000

Now I am wondering if I want to compare a value eg. 00000001 if it is to high/low, do I check without the most significant bit (FFFFFFF > 0000001 > 0000000) and check the most significant bit seperately (if > 7 => negative, else => positive) or is there a "smoother" way to do it?

Was it helpful?

Solution

Sometimes you may not want to have the overhead of comparing using JCInteger given in this answer of mine. If you just want to compare two signed, two complement, big endian numbers (the default Java integer encoding) in a byte array, then you can use the following code:

/**
 * Compares two signed, big endian integers stored in a byte array at a specific offset.
 * @param n1 the buffer containing the first number
 * @param n1Offset the offset of the first number in the buffer
 * @param n2 the buffer containing the second number
 * @param n2Offset the offset in the buffer of the second number
 * @return -1 if the first number is lower, 0 if the numbers are equal or 1 if the first number is greater
 */
public final static byte compareSignedInteger(
        final byte[] n1, final short n1Offset,
        final byte[] n2, final short n2Offset) {

    // compare the highest order byte (as signed)
    if (n1[n1Offset] < n2[n2Offset]) {
        return -1;
    } else if (n1[n1Offset] > n2[n2Offset]) {
        return +1;
    }

    // compare the next bytes (as unsigned values)
    short n1Byte, n2Byte;
    for (short i = 1; i < 4; i++) {
        n1Byte = (short) (n1[(short) (n1Offset + i)] & 0xFF);
        n2Byte = (short) (n2[(short) (n2Offset + i)] & 0xFF);

        if (n1Byte < n2Byte) {
            return -1;
        } else if (n1Byte > n2Byte) {
            return +1;
        }
    }
    return 0;
}

Note that this code is not optimized, it may be faster to unroll the loop, and it should be possible to do this with just byte arithmetic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top