getByAddress public static InetAddress getByAddress(byte[] addr) throws UnknownHostExceptionReturns an InetAddress object given the raw IP address . The argument is in network byte order: the highest order byte of the address is in getAddress()[0]. byte[] getAddress() Returns the raw IP address of this InetAddress object. 用这个方法啦
强制转换一下;b[0]=(byte)172;???????这样的话不是要丢失数据吗?
byte的范围是-128到127,超过127的需要处理一下 int i=...;//假设是一个byte byte b=i>127?(byte)(i-256):(byte)i;正队你这个问题应该是 byte[] ip=new byte[4]; ip[0]=(byte)(172-256); ...//后面你也就知道了啊
IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long 一个byte刚好可以放255 (0xFF=255)
public static InetAddress getByAddress(byte[] addr)
throws UnknownHostExceptionReturns an InetAddress object given the raw IP address . The argument is in network byte order: the highest order byte of the address is in getAddress()[0].
byte[] getAddress()
Returns the raw IP address of this InetAddress object. 用这个方法啦
int i=...;//假设是一个byte
byte b=i>127?(byte)(i-256):(byte)i;正队你这个问题应该是
byte[] ip=new byte[4];
ip[0]=(byte)(172-256);
...//后面你也就知道了啊
一个byte刚好可以放255 (0xFF=255)
都是直接强制转换的书上错啦?
这个问题老早以前就讨论过了
就是我这么处理的,呵呵byte是8位有符号位的,所以表示的范围是-128到127
如果一个大于127的数,那么其最高位就是1了,那么当作符号位就是负数了
这时候只要加256变成补码就对了
都是直接强制转换的
------
强制转换没有错啊
我上面的代码也是强制转换啊
只要要注意精度,只要是在byte范围内的强制转换都没有问题
大于127的就不能直接转换使用了。
谢谢啦又学到新东东啦感谢楼主
感谢大家!!!
感谢 jFresH_MaN(听说距离产生美,所以我将离开你!)
int i=...;//假设是一个byte
byte b=i>127?(byte)(i-256):(byte)i;正队你这个问题应该是
byte[] ip=new byte[4];
ip[0]=(byte)(172-256);
...//后面你也就知道了啊------------------------
这样的话ip[0] 不就成为负的了??这样对吗?
int i=...;//假设是一个byte
byte b=i>127?(byte)(i-256):(byte)i;正队你这个问题应该是
byte[] ip=new byte[4];
ip[0]=(byte)(172-256);
...//后面你也就知道了啊-------------
ip[0] = 84?