Compare two hex strings in Java?

本秂侑毒 提交于 2019-11-27 15:40:50

The values 0..9 and A..F are in hex-digit order in the ASCII character set, so

string1.compareTo(string2)

should do the trick. Unless I'm missing something.

BigInteger one = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",16);
BigInteger two = new BigInteger("0000000000000000000000000000000000000000",16);
System.out.println(one.compareTo(two));
System.out.println(two.compareTo(one));

Output:
1
-1

1 indicates greater than -1 indicates less than 0 would indicate equal values

Since hex characters are in ascending ascii order (as @Tenner indicated), you can directly compare the strings:

String hash1 = ...;
String hash2 = ...;

int comparisonResult = hash1.compareTo(hash2);
if (comparisonResult < 0) {
    // hash1 is less
}
else if (comparisonResult > 0) {
    // hash1 is greater
}
else {
    // comparisonResult == 0: hash1 compares equal to hash2
}

Since the strings are fixed length and '0' < '1' < ... < 'A' < ... < 'Z' you can use compareTo. If you use mixed case hex digits use compareToIgnoreCase.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!