有時你可能不想要使用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;
}
注意,該代碼沒有經過優化,它可能會更快到展開循環,並且應該可以僅用字節算術來做到這一點。
我假設你的意思是你想比較*兩個*值?如果是這樣,規範的方法是減去它們,看看結果的標誌是什麼。 –
以及我想知道一個數字是否在邊界之間,並且是正數或負數 – achiever
有什麼界限?如果一個有符號數是32位,它在7FFFFFFF和80000000之間 - 沒什麼可檢查的。 –