最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Function to convert Number to Binary string - Stack Overflow

programmeradmin1浏览0评论

Writing a function to convert passed in number to a binary string. The function is creating a proper binary sequence, but my pare function is skipping the first index when paring a number equal to binaryIndex[0] (ex. n = 32, 16, 8, 4). Any ideas why?

This step creates a binary ordered array, which is what I will use to check the passed in parameter with:

var Bin = function(n) {
  var x =1;
  var binSeq=[];
  var converted=[];
  for (var i=0; x <= n; i++) {
  binSeq.unshift(x)
  x = x+x
  }
  console.log(binSeq)

This next step should pare and spit out a binary sequence of 1's and 0's: but it is skipping if (n === binSeq[0])

for (var i=0; i < binSeq.length; i++) {
  if ((n - binSeq[i]) >= 0) {
  converted.unshift(1);
  n=n-binSeq[i]
  } else {converted.unshift(0)}
}
console.log(converted)
}

Link to the CodePen:

Writing a function to convert passed in number to a binary string. The function is creating a proper binary sequence, but my pare function is skipping the first index when paring a number equal to binaryIndex[0] (ex. n = 32, 16, 8, 4). Any ideas why?

This step creates a binary ordered array, which is what I will use to check the passed in parameter with:

var Bin = function(n) {
  var x =1;
  var binSeq=[];
  var converted=[];
  for (var i=0; x <= n; i++) {
  binSeq.unshift(x)
  x = x+x
  }
  console.log(binSeq)

This next step should pare and spit out a binary sequence of 1's and 0's: but it is skipping if (n === binSeq[0])

for (var i=0; i < binSeq.length; i++) {
  if ((n - binSeq[i]) >= 0) {
  converted.unshift(1);
  n=n-binSeq[i]
  } else {converted.unshift(0)}
}
console.log(converted)
}

Link to the CodePen: https://codepen.io/fdeppe/pen/GEozKY?editors=1111

Share Improve this question edited Jun 30, 2017 at 7:17 jeanpier_re 8351 gold badge6 silver badges23 bronze badges asked Jun 28, 2017 at 18:49 Francisco DeppeFrancisco Deppe 211 silver badge6 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 10

Actually this would do the trick

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}

Explanation here ==> Negative numbers to binary string in JavaScript

-3 >>> 0 (right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's plement representation of -3.

发布评论

评论列表(0)

  1. 暂无评论