tags:

views:

283

answers:

4

Hello all.I would like to do a data transfer between two computers using datagram socket.Iam using the following line this way :

host=InetAddress.getByAddress("mypc",new byte[]{192,168,1,110});

but when i use the above statement i get this error :"Possible loss of precision"

So i cast the int to bytes this way :

InetAddress.getByAddress("mypc",new byte[]{(byte)192,(byte)168,(byte)1,(byte)110});

Would the above statement work now ???

+1  A: 

It might not, cos the max value for a byte is 127 and beyond that it would rollover to the negative -64 for 192, -88 for 168 and so on...

Ram
+2  A: 

java bytes are signed (stupid, I know) so larger than 127 is not possible.

See alnitaks' response for a more complete (and later:) answer.

extraneon
can you pls tell me how i can modify that statement so that the commn. can be made ?
arshad
Don't bother with that link; that snippet belongs on http://thedailywtf.com/. See @Alnitak's answer for how to treat bytes as if they were unsigned.
Alan Moore
+13  A: 

If you already have it in a string, just use getByName():

InetAddress host = InetAddress.getByName("192.168.1.110");

Using bytes is cluttered, and possibly dangerous (due to signed byts used in Java). Stick with Strings if you can.

Yuval A
Yes, this works, but it doesn't answer the actual question.
Alnitak
+4  A: 

There's no problem casting the positive integer literals into byte values, even if they overflow.

The InetAddress.getByAddress() function copes perfectly well with the fact that values exceeding 127 will be converted into negative numbers.

The only thing you need to watch out for is converting the signed bytes back into integers if you subsequently want to display them. This works fine:

byte b = (byte)192;
System.out.println(b); // outputs "-64"

int i = (b & 0xff);
System.out.println(i); // outputs "192"
Alnitak