2

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

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

can't you just do dec.toString(2)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.