JavaScript ip地址轉換為二進位制

antzone發表於2017-04-07

本章節分享一段程式碼例項,它實現了將ip地址轉換為二進位制效果。

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼執行程式碼
var praseIpToBinary = function(ipAddress){
  var numArray = ipAddress.split(".");
  if(numArray.length != 4){
    alert("輸入的IP有誤");
    return;
  }
  var returnIpStr = "";
  for (var i = 0; i < 4; i++) {
    var curr_num = numArray[i];
    var number_Bin = parseInt(curr_num);
    number_Bin = number_Bin.toString(2);
    var iCount = 8-number_Bin.length;
    for (var j = 0; j < iCount; j++) {
      number_Bin = "0"+number_Bin;
    }
    returnIpStr += number_Bin;
  }
  return returnIpStr;
}
var ip="192.168.0.123";
console.log(praseIpToBinary(ip));

相關文章