[英]How to get the 1's complement of just necessary number of bits, rather than getting complement of all 32 bits representation of the number in java?
[英]How to get 32 bits unique number in Java?
我需要在Java中生成唯一的32位數字。 我需要將數字返回為Java int,這是接口所必需的。 能否請您分享一些想法?
該數字將用作MySQL PK,並且多個線程可以同時生成自己的唯一ID。 (很抱歉,決定不使用MySQL增量ID)
我嘗試了UUID類,但似乎它生成的數據具有比我可以使用的更多的位。
我發現了這一點,但不確定是否可行:
// seems no way to get int
UUID id = UUID.randomUUID();
System.out.println(id);
// not working either?
java.rmi.server.UID uid = new java.rmi.server.UID();
System.out.println(uid.toString());
// the one i am using
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
prng.setSeed(System.currentTimeMillis());
int ret = prng.nextInt();
System.out.println(ret);
您要有多“獨特”? 簡而言之,沖突域是什么? 如果要處理成千上萬個鍵,則Random.nextInt()會相對於您嘗試使用版本4 UUID(UUID v4生成128個隨機位)進行准確的操作。
如果您需要發生沖突的可能性較小的東西,則需要具有一個全局遞增的整數,但是這里要多加注意,例如保持JVM啟動之間的狀態。 為此,您應該查看AtomicIntegers 。
SecureRandom
方法很好,但不要在上面設置種子。 它將以(大概)安全的方式選擇自己的種子。
您也可以使用UUID並丟棄不需要的位,例如
int key = (int)UUID.randomUUID().getLeastSignificantBits();
編輯:您還應該知道, SecureRandom
的速度明顯比Random
慢。 由於您不在這里進行加密,為什么不使用Random
?
我認為您可以使用32位哈希函數。 詳細信息在以下教程中提供:http://www.concentric.net/~ttwang/tech/inthash.htm
private static int hash(int key){
key = ~key + (key << 15); // key = (key << 15) - key - 1;
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057; // key = (key + (key << 3)) + (key << 11);
key = key ^ (key >>> 16);
return key;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.