面试题,把IP地址保存到Int类型变量中

在新浪微博面试过程中遇到的问题,由于准备不充分,并没有答出来,回来搜索整理之后答案如下

//代码片段
package com.zwx;  
  
public class test {  
    public static void main(String[] args) {  
        byte[] bt = new byte[4];  
        bt[0] = (byte)192;  
        bt[1] = (byte)128;  
        bt[2] = 1;  
        bt[3] = (byte)255; //相当于 bt[3] = -1;
          
        int i = byteArrayToInt(bt);    
        System.out.println("int--->" + i);  
          
        byte[] b = intToByteArrayl(i);  
        System.out.print("ip--->");  
        for (byte bb : b) {  
           System.out.print(Byte.toUnsignedInt(bb) + ".");  
           //或者:System.out.print((bb & 0xFF) + ".");
        }  
    }  
      
    //int转ip(字节数组)  
    public static byte[] intToByteArrayl(int i) {     
        byte[] result = new byte[4];     
        result[0] = (byte)((i >> 24) & 0xFF);  
        result[1] = (byte)((i >> 16) & 0xFF);  
        result[2] = (byte)((i >> 8) & 0xFF);   
        result[3] = (byte)(i & 0xFF);  
        return result;  
    }  
      
    //ip(字节数组)转int  
    public static int byteArrayToInt(byte[] b) {  
        int value = 0;  
        for (int i = 0; i < 4; i++) {  
           value |= (b[i] & 0xFF);  
           if ( i < 3 ) {  
             value = value << 8;  
           }
           //System.out.println(Integer.toBinaryString(value));
        }  
        return value;  
    }  
      
} 

运行结果:

int--->-1065352705

ip--->192.128.1.255.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值