Code Junkie
Code Junkie

Reputation: 7788

New to hashcode and need help understanding code snippet

I have the following code snippet and need some help understanding a few pieces of it.

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);

Lastly, if I wanted to generate a file name from the two directories, would I just setup another string builder without the File.separator, or would it be more efficient to build the string first without the file separator, then split up the string?

Upvotes: 0

Views: 105

Answers (2)

arcy
arcy

Reputation: 13103

255 is 0FF hex, 0 1111 1111 binary.

A mask used with the 'and' operator ("&") is used to isolate the bits of the value to which the mask is anded -- an integer anded with the above mask results in an integer with the same lowest-order 8 bits as the original integer.

An integer put through >> 8 is shifted to the right 8 bits; anding with the same mask after that isolates those 8 bits, which started out as the next-higher-order 8 bits in the original integer.

Don't worry about efficiency unless you can show that a few microseconds is going to make a difference. Worry about making your code understandable enough that someone doesn't have to post to stackoverflow to understand it.

Upvotes: 1

Thilo
Thilo

Reputation: 262464

That code is just silly.

If you want to create two randomly distributed two-digit hex codes derived from a random UUID, you can just use the first four hex digits of the UUID itself.

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

A random UUID is a cryptographically strong random binary string (except for a few fixed digits to denote that this is a type-4 UUID). Any hashing and bit shifting or masking will just degrade the randomness.

Upvotes: 1

Related Questions