[英]How can i generate a long hash of a String?
我有一個 java 應用程序,我想在其中為字符串生long
ID(以便將這些字符串存儲在neo4j 中)。 為了避免數據重復,我想為存儲在long
整數中的每個字符串生成一個 id,每個字符串應該是唯一的。 我怎樣才能做到這一點 ?
這段代碼將計算相當不錯的哈希:
String s = "some string";
long hash = UUID.nameUUIDFromBytes(s.getBytes()).getMostSignificantBits();
你為什么不看看String的hashcode()
函數,只是采用它來代替長值?
順便說一句。 如果有辦法為每個String創建一個唯一的ID,那么你會找到一個壓縮算法,它能夠將每個String打包成8個字節(根據定義不可能)。
long
有64位。 長度為9的String
有72位。 從鴿子洞的原則 - 你不能得到一個獨特的哈希9長字符long
。
如果你仍然想要一個long
哈希:你可以為hash1()
String->int
, hash1()
和hash2()
獲取兩個標准的[不同!]哈希函數並計算: hash(s) = 2^32* hash1(s) + hash2(s)
有很多答案,請嘗試以下方法:
long
要求。 Mea culpa。 或者,如前所述,查看來源。
PS。 另一種技術是維護字符串字典:由於你不太可能很快得到2 64個字符串,你可以擁有完美的映射。 請注意,映射可能也成為一個主要瓶頸。
通過結合 CRC32 和 Adler32 可以實現一個簡單的 64 位散列。
Java 中的示例:
package com.example;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
public class MySimpleHash {
/**
* Calculate a 64 bits hash by combining CRC32 with Adler32.
*
* @param bytes a byte array
* @return a hash number
*/
public static long getHash(byte[] bytes) {
CRC32 crc32 = new CRC32();
Adler32 adl32 = new Adler32();
crc32.update(bytes);
adl32.update(bytes);
long crc = crc32.getValue();
long adl = adl32.getValue();
return (crc << 32) | adl;
}
public static void main(String[] args) {
String string = "This is a test string";
long hash = getHash(string.getBytes());
System.out.println("output: " + hash);
}
}
output: 7732385261082445741
Python 中的示例:
#!/usr/bin/python3
import zlib
def get_hash(bytes):
return zlib.crc32(bytes) << 32 | zlib.adler32(bytes)
string = "This is a test string"
hash = get_hash(string.encode())
print("output:", hash)
output: 7732385261082445741
這個Gist比較了一些hash方法: https : //gist.github.com/fabiolimace/507eac3d35900050eeb9772e5b1871ba
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.