在CoffeeScript中,我如何将IP(标准IPv4 127.0.0.1)转换为整数?
编辑:这里有很多很棒的答案,谢谢大家!
答案 0 :(得分:3)
ipStringToInteger = (x) ->
res = 0
(res = res * 256 + Number(y) for y in x.split("."))
res
编译为
var ipStringToInteger;
ipStringToInteger = function(x) {
var res, y, _i, _len, _ref;
res = 0;
_ref = x.split(".");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
y = _ref[_i];
res = res * 256 + Number(y);
}
return res;
};
简短的纯Javascript实现
var ipV4StringToInteger = function(string) {
var parts = string.split(".");
var sum = 0;
for(var i = 0; i < 4; i++) {
var partVal = Number(parts[i]);
sum = (sum << 8) + partVal;
}
return sum;
};
良好的纯Javascript实现
var ipV4StringToInteger = function(string) {
var parts = string.split(".");
if(parts.length != 4)
throw new Error("IPv4 string does not have 4 parts.");
var sum = 0;
for(var i = 0; i < 4; i++) {
var part = parts[i];
if(!part.match("^\\d+$"))
throw new Error("Non-digit, non-period character in IPv4 string.");
var partVal = Number(part);
if(partVal > 255)
throw new Error("IPv4 string contains invalid value.");
sum = (sum << 8) + partVal;
}
return sum;
};
答案 1 :(得分:2)
我将采用位移方法:
ip_to_int = (value) ->
result = 0
for part, i in value.split "."
result |= part << (3-i) * 8
result
使用它很简单:
alert ip_to_int "127.0.0.1"
答案 2 :(得分:2)
要将ip转换为整数,您需要公式
(first octet * 256³) + (second octet * 256²) + (third octet * 256) + (fourth octet)
让ip = '127.0.0.1'
,可以写成:
integer = 0
for octet, i in ip.split('.')
integer += octet * Math.pow 256, 3-i
可以使用reduce方法进行简化:
integer = ip.split('.').reduce ((t, n) -> t*256 + parseInt n), 0
答案 3 :(得分:1)
我相信@ellisbben打了它,但我以为我会在另一个JS版本上进行更多的错误检查。
function ip2int(ip){
// split them in to their own numbers
var octets = ip.split('.');
// make sure we have a valid IP. (length-wise)
if (octets.length!=4) return false;
// begin parsing
var result = 0;
for (var v = 1; v <= 4; v++){
var i = parseInt(octets[v-1],10);
// valid number?
if (isNaN(i) || i < 0 || i > 255) return false;
result += (i * Math.pow(256,(4-v)));
}
return result;
}
alert(ip2int('127.0.0.1'));
答案 4 :(得分:0)
这是另一种位移法。
addr='192.168.5.253'.split('.');
ipInt = (+addr[0] << 24) + (+addr[1] << 16) + (+addr[2] << 8) + (+addr[3]);
要扭转它......
[ipInt >> 24 & 0xff,ipInt >> 16 & 0xff,ipInt >> 8 & 0xff,ipInt & 0xff].join('.');
答案 5 :(得分:0)
抱歉,这是JS版本,但很容易将其转换为CoffeeScript:
// 'x.x.x.x' -> number
function Ip4ToInt(ip4str) {
var addr = ip4str.split('.');
if ( addr.length !== 4 || addr.some( (elm) => (parseInt(elm) > 255 || parseInt(elm) < 0 ) ) ) {
throw new Error('Invalid ip4 string: ' + ip4str);
}
return ((addr[0] << 24) >>> 0) + ((addr[1] << 16) >>> 0) + ((addr[2] << 8) >>> 0) + (addr[3]);
}
// number -> 'x.x.x.x'
function IntToIp4(ip4int){
return [ip4int >> 24 & 0xff,ip4int >> 16 & 0xff,ip4int >> 8 & 0xff,ip4int & 0xff].join('.');
}
答案 6 :(得分:-1)
node.js的最小解决方案:
function ip2int(ip) {
var ipint = 0;
ip.split('.').map(function (e, i) {
ipint += Math.pow(256, 3-i) * e;
});
return ipint;
}
console.log(ip2int('10.1.1.20'));