ip字符串与byte[]互转 和 mac字符串与byte[]互转

来源:互联网 发布:云计算课程教学大纲 编辑:程序博客网 时间:2024/05/22 04:58

//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;
}

原创粉丝点击