Compare two hex strings in Java?

15,155

Solution 1

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.

Solution 2

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

Solution 3

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
}
Share:
15,155
tree-hacker
Author by

tree-hacker

Updated on June 14, 2022

Comments

  • tree-hacker
    tree-hacker almost 2 years

    I am implementing a simple DHT using the Chord protocol in Java. The details are not important but the thing I'm stuck on is I need to hash strings and then see if one hashed string is "less than" another.

    I have some code to compute hashes using SHA1 which returns a 40 digit long hex string (of type String in Java) such as:

    69342c5c39e5ae5f0077aecc32c0f81811fb8193
    

    However I need to be able to compare two of these so to tell, for example that:

    0000000000000000000000000000000000000000
    

    is less than:

    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    

    This is the complete range of values as the 40 digit string is actually representing 40 hex numbers in the range 0123456789ABCDEF

    Does anyone know how to do this?

    Thanks in advance.

  • Chad Okere
    Chad Okere over 13 years
    As long as the strings are always going to be the same length, and case.
  • James Cronen
    James Cronen over 13 years
    @Chad: I'm assuming that's true since he's using a canned SHA1 algorithm.
  • Poindexter
    Poindexter over 13 years
    @Chad and Tenner: Even if it's not, it's rather easy to pad length and unify the cases.