N-ZOO / everycode

前端每日一练
163 stars 18 forks source link

[js] ip地址解析 #12

Open VaJoy opened 8 years ago

VaJoy commented 8 years ago
//把已知的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 commented 8 years ago
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 commented 8 years ago
   //本题其实就是考二进制,十进制之间的转换,贴一个没有容错处理的吧
   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 commented 8 years ago

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

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

@VaJoy 6666666666 v神

langmao commented 8 years ago

@VaJoy 绝对牛逼!!!

yulanggong commented 8 years ago

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

horsefefe commented 8 years ago

果断收藏了