天天看點

ip字元串與byte[]互轉 和 mac字元串與byte[]互轉

//ip字元串轉byte[]

String targetIPStr="192.168.1.1";

byte[] targetIP=new byte[4];

int i=0;

for(String str:targetIPStr.split("[.]")){

targetIP[i++]=(byte)(Integer.parseInt(str));

}

//mac字元串轉byte[]

String targetMacStr="";

byte[] targetMac=new byte[6];

int j=0;

for(String str:targetMacStr.split("[:]")){

targetMac[j++]=(byte)(Integer.parseInt(str, 16));

static int byte2int(byte b){

if(b>=0){

return b;

}else{

return b+256;

}

}

static byte[] ipstr2ipbyte(String ipstr){

byte[] ip=new byte[4];

int i=0;

for(String str:ipstr.split("[.]")){

ip[i++]=(byte)Integer.parseInt(str);

}

return ip;

}

static String ipbyte2ipstr(byte[] ip){

String ipStr="";

for(int i=0;i<ip.length;i++){

ipStr+=Integer.toString(byte2int(ip[i]));

if(i<(ip.length-1)){

ipStr+=":";

}

}

return ipStr;

}

static byte[] macstr2macbyte(String macstr){

byte[] mac=new byte[6];

int i=0;

for(String str:macstr.split("[:]")){

mac[i++]=(byte)Integer.parseInt(str, 16);

}

return mac;

}

static String macbyte2macstr(byte[] mac){

String macStr="";

for(int i=0;i<mac.length;i++){

macStr+=Integer.toHexString(mac[i]&0xFF);

if(i<(mac.length-1)){

macStr+="-";

}

}

return macStr;

}