azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.85k stars 260 forks source link

【每日一题】– 2019-10-12 - IP地址存储 #42

Closed azl397985856 closed 5 years ago

azl397985856 commented 5 years ago

将IP地址转化为32字节存储,并支持反向解析为原IP地址。

比如:

"192.168.0.1" - > 13232323 (一个数字,这个数字的范围不能超过32个字节的表示范围)

13232323 -> "192.168.0.1"

实现函数:

function IP2Int(str) {
}

function Int2IP(int) {
}
azl397985856 commented 5 years ago
function IP2Int(str) {
  // "192.168.0.1"
  let n = BigInt(0);
  // a << 1
  // a << 2
  str
    .split('.')
    .reverse()
    .forEach((c, i) => {
      n += BigInt(+c) << BigInt(8 * i);
    });

  return n; // 2^31 - 1
}

IP2Int("192.168.0.1")