簡體   English   中英

將兩個字節 arrays 與 java 中的大於或小於運算符進行比較

[英]compare two byte arrays with greater than or less than operator in java

所以我有兩個 arrays

byte[] arr1 = new byte[] {(byte)255, (byte)160, (byte)70, (byte)50, (byte) 90};
byte[] arr2 = new byte[] {(byte)255, (byte)170, (byte)60, (byte)55, (byte) 90};

我想檢查其中一個是否大於另一個。 類似於compare (byte[] arr1, byte[] arr2)方法的東西,它返回-1, 0, 1

在此示例中,該方法應返回arr2大於arr1

我怎樣才能在 java 中實現這樣的東西。 還是已經有本地方法?

我給你做了一個 function,它完全符合你的要求。 它逐步比較 2 Byte Arrays 並返回一個 int 和結果

public static int compareArrays(byte[] arr1, byte[] arr2) {
    // First choose the smallest array of the two (to prevent an IndexOutOfBoundsException)
    int smallestLength = Math.min(arr1.length, arr2.length);
    
    // Go through each byte step by step and compare
    for(int i = 0; i < smallestLength; i++) {
        if(arr1[i] > arr2[i]) {
            return 1;
        }
        if(arr1[i] < arr2[i]) {
            return -1;
        }
    }
    if(arr1.length > arr2.length) {
        return 1;
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM