2013-12-12 26 views
4

我必須使用java卡中的整數,但由於卡本身不支持整數,我使用byte []來代替。比較帶符號的十六進制數

要表示十六進制格式的數字,我檢查第一位,如果它是1 - 負數,如果它是0 - 正數(二進制明智)。所以,如果領先位小於8,則爲正,否則爲負(十六進制)。

次數最多:7FFFFFFF

最低數量:8000

現在我想知道如果我想比較值如。 00000001如果它是高/低,我是否檢查沒有最高有效位(FFFFFFF> 0000001> 0000000)並單獨檢查最高有效位(如果> 7 =>負,否則=>正)或是否存在「平滑器「做到這一點的方法?

+0

我假設你的意思是你想比較*兩個*值?如果是這樣,規範的方法是減去它們,看看結果的標誌是什麼。 –

+0

以及我想知道一個數字是否在邊界之間,並且是正數或負數 – achiever

+0

有什麼界限?如果一個有符號數是32位,它在7FFFFFFF和80000000之間 - 沒什麼可檢查的。 –

回答

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

注意,該代碼沒有經過優化,它可能會更快到展開循環,並且應該可以僅用字節算術來做到這一點。

+0

使用一百萬個隨機數進行測試,並使用MIN,-1,0,+1和MAX值進行一百萬次測試。補償沒有經過測試,但嘿... –

+0

高度讚賞 – achiever

相關問題