简体   繁体   English

比较Java中的两个十六进制字符串

[英]Compare two hex strings in Java?

I am implementing a simple DHT using the Chord protocol in Java. 我正在使用Java中的Chord协议实现一个简单的DHT。 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: 我有一些使用SHA1计算哈希值的代码,它返回一个40位长的十六进制字符串(Java中的String类型),例如:

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 这是完整的值范围,因为40位数字符串实际上代表0123456789ABCDEF范围内的40个十六进制数字

Does anyone know how to do this? 有谁知道如何做到这一点?

Thanks in advance. 提前致谢。

The values 0..9 and A..F are in hex-digit order in the ASCII character set, so 0..9A..F在ASCII字符集中以十六进制顺序排列,因此

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 -1

1 indicates greater than -1 indicates less than 0 would indicate equal values 1表示大于-1表示小于0表示相等的值

Since hex characters are in ascending ascii order (as @Tenner indicated), you can directly compare the strings: 由于十六进制字符按升序ascii顺序(如@Tenner所示),您可以直接比较字符串:

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 . 由于字符串是固定长度和'0'<'1'<... <'A'<... <'Z',您可以使用compareTo If you use mixed case hex digits use compareToIgnoreCase . 如果使用混合大小写十六进制数字,请使用compareToIgnoreCase

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM