面试题,把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.


猜你喜欢

转载自blog.csdn.net/playadota/article/details/77967776