从 MAC 地址递增十六进制字符串

Wil*_*iam 4 javascript parsing hex split

我正在尝试进行一些字符串操作。有没有办法在没有大量 if 语句的情况下做到这一点。

对于给定的 MAC 地址,我需要将最后一个值更改为 +1。例如:

84:1D:A2:B9:A3:D0 => Needs to change to: 84:1D:A2:B9:A3:D1
84:1D:A2:B9:A3:99 => Needs to change to: 84:1D:A2:B9:A3:A0
84:1D:A2:B9:A3:AF => Needs to change to: 84:1D:A2:B9:A3:B0

var _cnames = "84:8D:C7:BB:A3:F0";
var res = _cnames.slice(15, 17);
if(res[1] == "0" || res[1] == "1" || res[1] == "2" || res[1] == "3"
|| res[1] == "4" || res[1] == "5" || res[1] == "6" || res[1] == "7"
|| res[1] == "8" || res[1] == "A" || res[1] == "B" || res[1] == "C"
|| res[1] == "D" || res[1] == "E"){
    res = res[0] + String.fromCharCode(res.charCodeAt(1) + 1);
}
if(res[1] == "F"){
    if(res[0] == "9"){
    res = "A0";
  }else{
        res = String.fromCharCode(res.charCodeAt(0) + 1) + "0";
  }
}
if(res[1] == "9"){
    res = res[0] + "A";
}
console.log(res);
Run Code Online (Sandbox Code Playgroud)

这是我目前的解决方案,但它并不像我希望的那样高效。必须有更好的方法来解决这样的问题。

Joh*_*vek 5

JS 中非基数 10 中的数学

对此有一个非常简单的答案。该函数parseInt()接受第二个参数,即传入值的基数。例如

parseInt("F0", 16) // Tells us that this is a base 16 (hex) number.
Run Code Online (Sandbox Code Playgroud)

这将使我们转换为十进制。现在toString()Number 类型的方法也接受输出值的基数。所以如果我们把它放在一起,它看起来像这样。

(parseInt("F0", 16) + 1 ).toString(16) // returns f1
Run Code Online (Sandbox Code Playgroud)

这需要 value F0,一个十六进制数,将其转换为十进制加上 1,然后返回一个十六进制字符串。

我希望这有帮助!

编辑

为了更具体地回答您的问题,mac 地址的上下文是 00-FF,因此下面的内容将正确填充前导零,并使用模数将 FF 上的任何数字“包装”回 00 并再次向上。

("0"+ ((parseInt("FF", 16) + 1) % 256 ).toString(16)).substr(-2)
Run Code Online (Sandbox Code Playgroud)