-1

This might be something obvious but i'am missing it. Why do i need to perform AND with 0xff to obtain ip address? The way i see it is exactly the same thing, perform AND with 0xff should leave the bits the same, so why doesn't it work if i don't do the AND operation?

package com.inet.ex1;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ShowIP {
    public static void main(String[] args) {
        InetAddress host;
        try {
            host = InetAddress.getLocalHost();
            byte[] ip = host.getAddress();
            for (int i = 0; i < ip.length; i++) {
                if (i == 0) System.out.print(ip[i] & 0xff);
                else System.out.print("." + (ip[i] & 0xff));
            }
        } catch (UnknownHostException e) {
            System.out.println(e);
        }
    }
}
user207421
  • 305,947
  • 44
  • 307
  • 483
vanmarcke
  • 133
  • 1
  • 1
  • 7
  • 1
    What does "doesn't work" mean? What result or error do you get and what is the expected result? – dunni Mar 26 '17 at 22:27
  • Sorry it works but it shows negative numbers! – vanmarcke Mar 26 '17 at 22:34
  • From what you've described, it looks like the real question is what `& 0xff` does in Java. The marked duplicate should answer that. If I misunderstood you or that question didn't answer your question, please mention me with @yshavit and I can re-open it -- but in that case, please clarify what other info you're looking for. – yshavit Mar 26 '17 at 22:36
  • Oh, and note that there is no overload for `PrintStream.print(byte)`, so when you pass in a byte, it gets cast to an int, and passed to `print(int)`. That may be part of what's missing in your understanding. – yshavit Mar 26 '17 at 22:38

1 Answers1

0

I suppose because byte is a primitive data type signed. It has a minimum value of -128 and a maximum value of 127 (inclusive).

In this case each byte in the array contains an unsigned value, so when you execute the bitwise AND operator with 0xff (an integer) the result is also an int.

freedev
  • 25,946
  • 8
  • 108
  • 125