59 lines
1.4 KiB
Java
59 lines
1.4 KiB
Java
package node;
|
|
|
|
import java.nio.ByteBuffer;
|
|
import java.util.Random;
|
|
|
|
public class Identifier {
|
|
private static Random random = new Random(System.currentTimeMillis());
|
|
|
|
private int id;
|
|
private boolean bits[] = new boolean[Node.ID_BITS];
|
|
|
|
public Identifier(int id) {
|
|
this.id = id;
|
|
|
|
String bitstring = Integer.toBinaryString(id);
|
|
for (int i = bitstring.length(); i > 0; i--) {
|
|
bits[bits.length - i] = bitstring.charAt(bitstring.length() - i) == '1';
|
|
}
|
|
}
|
|
|
|
public static Identifier getRandomIdentifier() {
|
|
int max_value = (int) Math.pow(2, Node.ID_BITS);
|
|
int id = (int) Math.abs((Math.round((max_value / 2)
|
|
+ random.nextGaussian() * (max_value / 2)) % max_value));
|
|
return new Identifier(id);
|
|
}
|
|
|
|
public int getId() {
|
|
return id;
|
|
}
|
|
|
|
public int distanceTo(Identifier otherID) {
|
|
return id ^ otherID.getId();
|
|
}
|
|
|
|
public boolean isBitSetAt(int index) {
|
|
return bits[index];
|
|
}
|
|
|
|
public byte[] getBytes() {
|
|
ByteBuffer result = ByteBuffer.allocate(4);
|
|
result.putInt(id);
|
|
return result.array();
|
|
}
|
|
|
|
@Override
|
|
public boolean equals(Object o) {
|
|
if (!(o instanceof Identifier)) {
|
|
return false;
|
|
} else {
|
|
return id == ((Identifier) o).getId();
|
|
}
|
|
}
|
|
|
|
public String toString() {
|
|
return String.valueOf(id);
|
|
}
|
|
}
|