读书人

惭愧求教!关于amp;后面跟一个16进制数的

发布时间: 2013-08-04 18:26:16 作者: rapoo

惭愧求教!关于&后面跟一个16进制数的问题


public final static synchronized String generate(Object o) {
long id1 = System.currentTimeMillis() & 0xFFFFFFFFL;
long id2 = System.identityHashCode(o);
long id3 = randomLong( -0x80000000L, 0x80000000L) & 0xFFFFFFFFL;

id1 <<= 16;
id1 += (id2 & 0xFFFF0000L) >> 16;
id3 += (id2 & 0x0000FFFFL) << 32;

String str = Format.convert(id1, 6, chars64) +
Format.convert(id3, 6, chars64);
//return locate + time + "_" + md5.getMD5ofStr(str);
return md5.getMD5ofStr(str);
}



public final synchronized static String generate() {
long id1 = System.currentTimeMillis() & 0x3FFFFFFFL;
long id3 = randomLong( -0x80000000L, 0x80000000L) & 0x3FFFFFFFL;

String str = Format.convert(id1, 6, chars64) +
Format.convert(id3, 6, chars64);
//return locate + time + "_" + md5.getMD5ofStr(str);
return md5.getMD5ofStr(str);
}


上面这两段代码中的"long id1 = System.currentTimeMillis() & 0x3FFFFFFFL;"
与“long id1 = System.currentTimeMillis() & 0xFFFFFFFFL;”
与“id3 += (id2 & 0x0000FFFFL) << 32;”
分别是有什么样作用的? 搞不清楚为什么要这样写?
[解决办法]
据说这样的写法运算起来更高效,不过我觉得没那个必要,咱还没到挑战计算机性能的那个水平。
&是与运算,
比如
6&7
转成2进制
0000000...1010
0000000...1011
等于:.....1010
就是结果为6
0xFFFFFFFFL


至于这个的话,
一个F就等于11111111
L代表long的标记
<<是移位操作。
[解决办法]
System.currentTimeMillis() & 0xFFFFFFFFL
取余数的意思 JAVA的源码中经常用到的, 舍弃System.currentTimeMillis 32位以上的内容
(id2 & 0x0000FFFFL) << 32
同理,取模并左移32位。
至于为什么要这样做, 这个算法的作用应该是去除重复发生的几率(我记得在HASHSET的算法中也看到了这个算法的应用)。

读书人网 >Java相关

热点推荐