问题
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:
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 String
s if you can.
回答2:
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"
回答3:
java bytes are signed (stupid, I know) so larger than 127 is not possible.
See alnitaks' response for a more complete (and later:) answer.
回答4:
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...
来源:https://stackoverflow.com/questions/755715/is-this-statement-correct-in-java