Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] ip地址解析 #12

Open
VaJoy opened this issue Dec 26, 2015 · 7 comments
Open

[js] ip地址解析 #12

VaJoy opened this issue Dec 26, 2015 · 7 comments

Comments

@VaJoy
Copy link
Member

VaJoy commented Dec 26, 2015

//把已知的ip二进制数值联合起来的十进制值,反解码为IP形式
// 如 2149583361 > 10000000 00100000 00001010 00000001 > "128.32.10.1"
function decodeIp(int32) {
  //TODO: 返回对应的ip地址
}
console.log(decodeIp(2149583361));  //"128.32.10.1"
@overkazaf
Copy link

function decodeIp(int32) {
    //TODO: 返回对应的ip地址
    if(isNaN(int32) || parseInt(int32) != int32) throw new Error('Parameter illegal');
    var i, s = '', arr = [], dec;
    for (i = 0; i < 32; int32 >>= 1, i++) {

        s = int32 & 1 ? '1' + s : '0' + s;

        if ((i + 1) % 8 === 0) {
            dec = parseInt(s, 2);
            if (dec < 0 || dec > 255) {
                throw new Error('Not a valid ip addr');
            }
            arr.unshift(dec);
            s = '';
        }
    }
    return arr.join('.');
}

console.log(decodeIp(2149583361));

@langmao
Copy link
Member

langmao commented Dec 27, 2015

   //本题其实就是考二进制,十进制之间的转换,贴一个没有容错处理的吧
   function decodeIp(int32) {

      var byt = int32.toString(2), //2进制表示
          reg = /(?:[0-1]{8})/g; // 每八位一组

          //TODO 后期看看能有什么优化
          return byt.match(reg).map(function(num){
              return parseInt(num,2);//转换为十进制
          }).join(".");

  }

@VaJoy
Copy link
Member Author

VaJoy commented Dec 28, 2015

@langmao 写的不错。我也贴个有趣的,位计算

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

@langmao
Copy link
Member

langmao commented Dec 28, 2015

@VaJoy 6666666666 v神

@langmao
Copy link
Member

langmao commented Dec 28, 2015

@VaJoy 绝对牛逼!!!

@yulanggong
Copy link

正好以前写过,凑个热闹
https://gist.github.com/yulanggong/3986143

@horsefefe
Copy link

果断收藏了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants