everycode icon indicating copy to clipboard operation
everycode copied to clipboard

2014年12月10日 D7

Open XadillaX opened this issue 11 years ago • 10 comments

今天题目比以往简单。

一个 IP 比如 128.32.10.1,我们能变成二进制:

  • 128: 10000000
  • 32: 00100000
  • 10: 00001010
  • 1: 00000001

把它们黏起来就变成了 10000000001000000000101000000001,变成十进制就是 2149583361

所以我们要做的是给你类似于 2149583361 这么个数字,你给还原成 IP。

function int32ToIp(int32) {
    //...
}

int32ToIp(2149583361); //< "128.32.10.1"

XadillaX avatar Dec 10 '14 03:12 XadillaX

发现题主换人了

function int32ToIp(int32) {
    return int32.toString(2).match(/\d{8}/g).map(function(s) {
        return parseInt(s, 2);
    }).join(".");
}

上个初版 然后再优化

Blueria avatar Dec 10 '14 03:12 Blueria

@Blueria

int32ToIp(149583361); //< "8.234.118.1"

XadillaX avatar Dec 10 '14 03:12 XadillaX

-. - 我在纠结我要不要发我的。

XadillaX avatar Dec 10 '14 03:12 XadillaX

优化一下 不足32位就前导零吧 :grin:

function int32ToIp(int32) {
    var bin  = int32.toString(2);
    bin = new Array(33 - bin.length).join("0") + bin;

    return bin.match(/\d{8}/g).map(function(s) {
        return parseInt(s, 2);
    }).join(".");
}

期待其他思路 @XadillaX 你是压轴的:sparkles: 表急着发

Blueria avatar Dec 10 '14 05:12 Blueria

function int32ToIp(int32) {
    var ret = "", i;

    for(i=3; i>=0; i--) {
        ret += parseInt(int32/(Math.pow(256, i)), 10);
        if(i !== 0)
            ret += ".";
        int32 = int32 % Math.pow(256, i);
    }

    return ret;
}

@XadillaX 其实2149583361这个数已经超出范围了,超过ox7FFFFFFF的整数都不准

businiaowa avatar Dec 10 '14 05:12 businiaowa

function int32ToIp(int32) {
    var bin = int32.toString(2).split(''), result = [];
    for(var i = 0; i < 4; i++) { result.push(parseInt(bin.splice(0, 8).join(''), 2));}
    return result.join('.');
}

// 测试用例
console.log(int32ToIp(2149583361)); //< "128.32.10.1"

只根据题目完成了答案,但是不知道如何做错误检测。

think2011 avatar Dec 10 '14 08:12 think2011

@businiaowa 有种类型是 unsigned int,只不过在 js 里面无法体现而已。而且 js 里面的数字长度是 double 范围的。

XadillaX avatar Dec 10 '14 08:12 XadillaX

function int32ToIp(int32) {
    return [ int32 / 2 >> 23, (int32 / 2 >> 15) % 256, (int32 / 2 >> 7) % 256, int32 % 256 ].join(".");
}

以及:

function int32ToIp(a){return[a/2>>23,(a/2>>15)%256,(a/2>>7)%256,a%256].join(".")}

XadillaX avatar Dec 10 '14 08:12 XadillaX

function int32ToIp(ip_int) {
  return (ip_int>>>24 & 0xff)+'.'+(ip_int >>> 16 & 0xff) + '.' + (ip_int >>> 8 & 0xff) + '.' + (ip_int & 0xff);
}

backsapce avatar Dec 11 '14 01:12 backsapce

中规中矩毫无惊喜的我:

    function int32ToIp(int32) {
      var r = "",
          binary = int32.toString(2);
      for(var i=0;i<4;i++){
        r = parseInt(binary.slice(-(i+1)*8,-i*8||32),2) + (i==0?"":".") + r
      }
      return r;
    }

VaJoy avatar Mar 03 '15 06:03 VaJoy