比较带符号的十六进制数

时间:2013-12-12 16:25:07

标签: java signed hex javacard

我必须在java卡中使用int,但由于卡本身不支持整数,我使用byte []代替。

要以十六进制格式表示数字,我检查第一位,如果它是1 - 负,如果它是0 - 正(二进制)。因此,如果前导位小于8则为正,否则为负(十六进制)。

最高人数:7FFFFFFF

最低号码:80000000

现在我想知道我是否想要比较一个值,例如。 00000001如果是高/低,是否在没有最高有效位(FFFFFFF> 0000001> 0000000)的情况下进行检查并单独检查最高有效位(如果> 7 =>负,否则=>正)或有没有“更顺畅”的方式呢?

1 个答案:

答案 0 :(得分:2)

有时您可能不希望使用JCInteger given in this answer of mine进行比较。如果您只想在字节数组中比较两个有符号,两个补码,大端数字(默认的Java整数编码),那么您可以使用以下代码:

/**
 * 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;
}

请注意,此代码未经过优化,展开循环可能会更快,并且应该可以通过字节算法完成此操作。

相关问题