Is this statement correct in java?

旧城冷巷雨未停 提交于 2019-12-14 03:52:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!