Francisco Deppe
Francisco Deppe

Reputation: 21

Function to convert Number to Binary string

Writing a function to convert passed in number to a binary string. The function is creating a proper binary sequence, but my compare function is skipping the first index when comparing 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 compare 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

Upvotes: 2

Views: 3357

Answers (1)

Sampgun
Sampgun

Reputation: 2977

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 complement representation of -3.

Upvotes: 10

Related Questions