gpt4 book ai didi

java - 比较带符号的十六进制数

转载 作者:搜寻专家 更新时间:2023-11-01 03:23:56 27 4
gpt4 key购买 nike

我必须在 java 卡中使用整数,但由于卡本身不支持整数,所以我改用 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;
}

请注意,此代码未优化,展开循环可能会更快,并且应该可以仅使用字节运算来完成此操作。

关于java - 比较带符号的十六进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20548759/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com