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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4259681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:34:02  来源:igfitidea点击:

Compare two hex strings in Java?

javastringhashhexsha1

提问by tree-hacker

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.

我正在使用 Java 中的 Chord 协议实现一个简单的 DHT。细节并不重要,但我坚持的事情是我需要散列字符串,然后查看一个散列字符串是否“小于”另一个。

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.

提前致谢。

回答by James Cronen

The values 0..9and A..Fare 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.

应该做的伎俩。除非我遗漏了什么。

回答by Adam

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 表示相等

回答by Adrian Pronk

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
}

回答by vitaut

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

由于字符串是固定长度的,并且 '0' < '1' < ... < 'A' < ... < 'Z' 您可以使用compareTo. 如果您使用大小写混合的十六进制数字,请使用compareToIgnoreCase.