visent
visent

Reputation: 13

Different results, why?

I have code for print MAC address from Java, the code is

InetAddress ip;
try {
    ip = InetAddress.getLocalHost();
    System.out.println("Current IP address : " + ip.getHostAddress());

    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

    byte[] mac = network.getHardwareAddress();

    System.out.print("Current MAC address : ");

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < mac.length; i++) {
         sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
    }
    System.out.println(sb.toString());


} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (SocketException e){
    e.printStackTrace();
}

but I has curiosity about this, and I'm trying to print directly with

System.out.print("Current MAC address : ");
for (int i = 0; i < mac.length; i++) {
         System.out.print(mac[i]);
              if (i < mac.length - 1) 
                   System.out.print("-");
              else
                   System.out.print("");
}

but it doesn't work.

The results are

Current MAC address : 08-00-27-96-40-39
Current MAC address : 8-0-39--106-64-57

why?

Thank's in advance for your help!!

Upvotes: 1

Views: 79

Answers (1)

Eran
Eran

Reputation: 394156

String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "") produces 2 hexadecimal digits for each element of the array.

On the other hand, your code prints the decimal representation of each element, so 27 (hex) becomes 39 (decimal), and so on.

If you replace

System.out.print(mac[i]);

with

System.out.print(Integer.toString (mac[i] & 0xff,16).toUpperCase ());

you'll get (almost) the same result.

Note that & 0xff is required in order to get the positive value of the integer whose 8 lowest bits are the same as the original byte. Without it the negative valued bytes (such as -106 in your example) will be printed as negative numbers.

For example, take the 4th byte, which your code prints as -106 :

First we want to get its unsigned value 150. Converting 150 from decimal to hexadecimal gives 96.

After that change the output of the 2 snippets is :

Current MAC address : 08-00-27-96-40-39
Current MAC address : 8-0-27-96-40-39

Note that the second snippet is still lacking the leading 0s for small numbers.

Upvotes: 3

Related Questions