## javascript中转换的几种方案：

var REG =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\$/;

### 方案1:每8位转成16进制字符,拼接后转成整数

function ipToInt(IP){
var xH = "",result = REG.exec(ip);
if(!result) return -1;
for (var i = 1; i <= 4; i++) {
var h = parseInt(result[i]);
xH += (h > 15 ? "" : "0") + h.toString(16);
}
return parseInt(xH, 16);
}

function ipToInt(IP){
return parseInt(IP.replace(/\d+\.?/ig,function(a){
a = parseInt(a);
return (a > 15 ? "" : "0") + a.toString(16);
}),16);
}

### 方案2:直接计算

function ipToInt(IP){
var xH = "",result = REG.exec(ip);
if(!result) return -1;
return (parseInt(result[1]) * 0x1000000
+ parseInt(result[2]) * 0x10000
+ parseInt(result[3]) * 0x100
+ parseInt(result[4]));
}

### 方案3:按位计算

function ipToInt(IP){
var xH = "",result = REG.exec(ip);
if(!result) return -1;
return (parseInt(result[1]) << 24
| parseInt(result[2]) << 16
| parseInt(result[3]) << 8
| parseInt(result[4]));
}

function ipToInt(IP){
var xH = "",result = REG.exec(ip);
if(!result) return -1;
return (parseInt(result[1]) << 24
| parseInt(result[2]) << 16
| parseInt(result[3]) << 8
| parseInt(result[4]))>>>0;
}

### 方案4:按位,字符串拼接结合（纯属于瞎折腾）

function ipToInt(IP) {
var xH = "",
result = REG.exec(ip);
if (!result) return - 1;
var ip2 = "000000" + ((parseInt(result[2]) << 16) | (parseInt(result[3]) << 8) | parseInt(result[4])).toString(16);
return parseInt(parseInt(result[1]).toString(16) + ip2.substr(ip2.length - 6), 16);
}

## 总结

function intToIp(INT){
if(INT < 0 || INT > 0xFFFFFFFF){
throw ("The number is not normal!");
}
return (INT>>>24) + "." + (INT>>16 & 0xFF) + "." + (INT>>8 & 0xFF) + "." + (INT & 0xFF);
}

posted on 2013-06-17 17:55  cnwhy  阅读(6026)  评论(2编辑  收藏