在 JavaScript 中转换时丢失了一点?

Losing a bit when converting in JavaScript?

假设我有一个 var testIP = '93.174.93.145';

我正在执行以下方法:

function ipToBin(ip) {
    var block = ip.split('.');
    var res = 0;

    res += block[0] << 24;
    res += block[1] << 16;
    res += block[2] << 8;
    res += block[3] << 0;

    bin = res.toString(2);
    console.log('\n to bin: ', bin);
    console.log(bin.length);
    return bin;
}

function binToIP(bin) {
    var block1 = (bin.split(0, 8));
    block1 = parseInt(block1, 2);
    block1 = (block1 >> 0) & 255;

    var block2 = bin.split(9, 8);
    block2 = parseInt(block2, 2);
    block2 = (block2 >> 8) & 255;

    var block3 = bin.split(17, 8);
    block3 = parseInt(block3, 2);
    block3 = (block3 >> 16) & 255;

    var block4 = bin.split(25, 8);
    block4 = parseInt(block4, 2);
    block4 = (block4 >> 24) & 255;

    console.log((block4 + '.' + block3 + '.' + block2 + '.' + block1).toString());
}


现在问题是二进制字符串的长度只有 31,当转换回 IP 时,它 returns 93.174.93.1。这类似于 this post 吗?或者我面临的问题到底在哪里?

主要问题是 toString(2) 只会输出它需要的数字,它只需要 31。所以当你在 binToIP 中进行字符串操作时,它依赖于32 位数字,你得到了错误的值。

我根本不会在 binToIP 中进行字符串操作,我只会做与您在 iptoBin 中所做的相反的操作:将其解析为数字,然后进行位操作以获取各个位,然后将它们组成一个字符串:

function binToIP(bin) {
  var value = parseInt(bin, 2);
  var block1 = (value & 0xFF000000) >> 24;
  var block2 = (value & 0x00FF0000) >> 16;
  var block3 = (value & 0x0000FF00) >> 8;
  var block4 = value & 0x000000FF;
  var ip = block1 + "." + block2 + "." + block3 + "." + block4;

  return ip;
}

实例:

var testIP = '93.174.93.145';
snippet.log("Original IP: " + testIP);
var bin = ipToBin(testIP);
snippet.log("bin: " + bin);
var rebuiltIP = binToIP(bin);
snippet.log("Rebuilt IP : " + rebuiltIP);

function ipToBin(ip) {
  var block = ip.split('.');
  var res = 0;

  res += block[0] << 24;
  res += block[1] << 16;
  res += block[2] << 8;
  res += block[3] << 0;

  bin = res.toString(2);
  return bin;
}

function binToIP(bin) {
  var value = parseInt(bin, 2);
  var block1 = (value & 0xFF000000) >> 24;
  var block2 = (value & 0x00FF0000) >> 16;
  var block3 = (value & 0x0000FF00) >> 8;
  var block4 = value & 0x000000FF;
  var ip = block1 + "." + block2 + "." + block3 + "." + block4;

  return ip;
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>