java 16进制比较_java – 比较带符号的十六进制数

我必须在

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

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

最高人数:7FFFFFFF

最低人数:80000000

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

最佳答案 有时您可能不希望使用

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;

}

请注意,此代码未经过优化,展开循环可能会更快,并且应该可以使用字节算法来执行此操作.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值