当前位置: 代码迷 >> J2SE >> 请问上Inet4Address的getAddress方法的返回结果
  详细解决方案

请问上Inet4Address的getAddress方法的返回结果

热度:66   发布时间:2016-04-24 00:29:42.0
请教下Inet4Address的getAddress方法的返回结果
Java code
//关于网络这块我不懂,所以来请教一下.public static void writeInet4Address(OutputStream output, Inet4Address value, int length) throws RTUException {        // 转化数据        Long lvalue = null;        if (value != null) {            byte[] bytes = value.getAddress();                        //debug时候,Inet4Address value的值为:/192.168.1.156                    //执行这句后,bytes 内容为[-64, -88, 1, -100],请教下这里是怎么变化/换算的.                 if (bytes == null || bytes.length != 4) {                throw new RTUException("不是标准的IPv4地址值.");            }                  //还有下面这些内容作用是什么,运行完后lvalue值为:3232235932. 再请教下换算过程.            lvalue = 0l;            lvalue += ((long) (bytes[0] & 0xFF) << 24);            lvalue += ((long) (bytes[1] & 0xFF) << 16);            lvalue += ((long) (bytes[2] & 0xFF) << 8);            lvalue += ((long) (bytes[3] & 0xFF) << 0);        }}


------解决方案--------------------
//debug时候,Inet4Address value的值为:/192.168.1.156
//执行这句后,bytes 内容为[-64, -88, 1, -100],请教下这里是怎么变化/换算的.
这没什么换算,"192"的2进制表示是"11000000",因为jav 里byte类行为有符号数,所以把“192”放进一个"byte"里,因其最高位是1,所以就是-64. "168"就是-88,“156”就是-100。
相当于把192 168 1 156 这4个数原封不动放进一个byte[]里了。


------解决方案--------------------
lvalue = 0l;
lvalue += ((long) (bytes[0] & 0xFF) << 24);
lvalue += ((long) (bytes[1] & 0xFF) << 16);
lvalue += ((long) (bytes[2] & 0xFF) << 8);
lvalue += ((long) (bytes[3] & 0xFF) << 0);

这作用是把ip转化为long型的数值了吧.下面的可以参考下:
http://tdcq.iteye.com/blog/1407169
------解决方案--------------------
Java code
//debug时候,Inet4Address value的值为:/192.168.1.156                    //执行这句后,bytes 内容为[-64, -88, 1, -100],请教下这里是怎么变化/换算的.
------解决方案--------------------
Inet4Address对象建立之时,有一个变量address已经存下了IP地址的int数据,执行getAddress方法,就将变量的address分成四组数字,并转换成byte返回。楼主可以看下源码返回过程。
------解决方案--------------------
((long) (bytes[0] & 0xFF) << 24);

bytes[0] & 0xFF 把bytes[0]转成int
<< 24 左移24,右侧补0
(long) 转成long

后面同理了,然后将值累加。