memcmp in Java, hooray. @param a First non-null byte array to compare. @param b Second non-null byte array to compare. @return 0 if the two arrays are identical, otherwise the difference between the first two different bytes, otherwise the different between their lengths.
(final byte[] a, final byte[] b)
| 1036 | * their lengths. |
| 1037 | */ |
| 1038 | public static int memcmp(final byte[] a, final byte[] b) { |
| 1039 | final int length = Math.min(a.length, b.length); |
| 1040 | if (a == b) { // Do this after accessing a.length and b.length |
| 1041 | return 0; // in order to NPE if either a or b is null. |
| 1042 | } |
| 1043 | for (int i = 0; i < length; i++) { |
| 1044 | if (a[i] != b[i]) { |
| 1045 | return (a[i] & 0xFF) - (b[i] & 0xFF); // "promote" to unsigned. |
| 1046 | } |
| 1047 | } |
| 1048 | return a.length - b.length; |
| 1049 | } |
| 1050 | |
| 1051 | /** |
| 1052 | * {@code memcmp(3)} with a given offset and length. |