StringBuilder sb = new StringBuilder();
for (int i = 0; i < 12; i++) {
sb.append(MAC_CHAR[rd.nextInt(15)]);
- if (i == 1) { // First 2 byte must be EVEN.
- if ((Integer.parseInt(sb.toString(), 16) % 2) == 1) {
- sb.delete(0, sb.length());
- i = -1;
- continue;
+ if (i == 1) {
+ // Most significant byte should satisfy following conditions.
+ // - 1st bit = 0 (least significant bit)
+ // - 2nd bit = 1
+ int firstByteInt = Integer.parseInt(sb.toString(), 16);
+ firstByteInt &= 252; // set last two bit zero.
+ firstByteInt |= 2; // set last two bit '10'.
+ StringBuilder hex = new StringBuilder(Integer.toHexString(firstByteInt));
+ if (hex.length() < 2) {
+ hex.insert(0, "0"); // padding zero.
}
+ sb.replace(0, 2, hex.toString());
}
if (i > 0 && i < 11 && (i % 2 == 1)) {
sb.append(":");