0

我有以下代码片段,需要一些帮助来理解其中的一些片段。

String fileName = UUID.randomUUID().toString();

int hashcode = fileName.hashCode();

//I'm not sure why we are creating a mask with an int of 255
int mask = 255;

//Wny are we adding 255 to the hashcode?
int firstDir = hashcode & mask;

//What does it mean to have (hashcode >> 8) & mask? If I were to build a third
// tier would I use (hashcode >> 16) $ mask?
int secondDir = (hashcode >> 8) & mask;

StringBuilder sb = new StringBuilder(File.separator);

//I noticed when using this %02 it truncates the directory to 2 chars, does this 
//just convert 3 digits to alpha numeric representing the same three digits?
sb.append(String.format("%02x", firstDir));

sb.append(File.separator);
sb.append(String.format("%02x", secondDir));
sb.append(File.separator);

最后,如果我想从两个目录生成一个文件名,我是否只是设置另一个没有 File.separator 的字符串构建器,还是先构建没有文件分隔符的字符串,然后拆分字符串更有效?

4

2 回答 2

1

那个代码很傻。

如果您想创建两个从随机 UUID 派生的随机分布的两位十六进制代码,您可以只使用 UUID 本身的前四个十六进制数字。

String fileName = UUID.randomUUID().toString();
String firstDir = fileName.substring(0,2);
String secondDir = fileName.substring(2,4);

随机 UUID 是加密强的随机二进制字符串(除了几个固定数字表示这是一个类型 4 UUID)。任何散列和位移或掩码只会降低随机性。

于 2013-10-01T03:15:42.357 回答
1

255 是 0FF 十六进制,0 1111 1111 二进制。

与“与”运算符 (“&”) 一起使用的掩码用于隔离与掩码进行与运算的值的位——与上述掩码进行与运算的整数会产生具有相同最低 8 位的整数作为原始整数。

通过 >> 8 的整数右移 8 位;之后使用相同的掩码隔离这 8 位,这些 8 位开始是原始整数中的下一个高阶 8 位。

不要担心效率,除非你能证明几微秒会产生影响。担心使您的代码足够易于理解,以至于有人不必发布到 stackoverflow 来理解它。

于 2013-10-01T03:18:51.227 回答