[英]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.