3

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 ???

arshad
  • 441
  • 4
  • 7
  • 14
  • 2
    Why don't you try it and find out? Surely that's better than trying this quiz approach. If it doesn't work, *then* come back and ask us why. – paxdiablo Apr 16 '09 at 11:36

4 Answers4

14

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 Adam
  • 161,610
  • 92
  • 305
  • 395
6

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
  • 334,560
  • 70
  • 407
  • 495
2

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
  • 23,575
  • 2
  • 47
  • 51
  • can you pls tell me how i can modify that statement so that the commn. can be made ? – arshad Apr 16 '09 at 11:42
  • 1
    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 Apr 17 '09 at 00:07
1

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...

Prabhu R
  • 13,836
  • 21
  • 78
  • 112