0

Problem statement: I'm trying to get string > binary without using the inbuilt method in javascript.

This is a piece of program where a string input (like "ABC") is accepted, then it is translated to an array of equivalent code value ([65,66,67]).

Function binary() will change a number to binary. But I'm unable to join them together to loop through all the contents. Please help. (I'm a noob, please forgive my bad code and bad explanation)

var temp3 = [65,66,67];
var temp2 = [];
var r;

for(i=0;i<temp3.length;i++) {
var  r = temp3[i];    
temp2.push(binary(r));
}

function binary(r) {
  if (r === 0) return;
  temp2.unshift(r % 2);
  binary(Math.floor(r / 2));
  return temp2;
}
console.log(temp2);
3
  • 1
    Welcome to SO! I took the liberty of moving you example code into a snippet. However, it does not run-- it looks like you have a syntax error at tempstring.forEach(items) where you are most likely meaning to be passing a function callback. Please fix your example code so it executes, and then it will be easier to provide you with additional guidance. Commented Jan 31, 2021 at 5:59
  • Alex, thank you for helping me. I'm facing trouble with joining for loop and function binary. Getting an error (Maximum call stack size exceeded) here when combined. These codes works individually. I hope this helps! Commented Jan 31, 2021 at 7:05
  • The value that returns from the recursive binary call isn't used, so there's no way your recursion will move forward - nothing changes between its calls Commented Jan 31, 2021 at 7:07

2 Answers 2

2

I think this is a cleaner version of this function. It should work for any non-negative integers, and would be easy enough to extend to the negatives. If we have a single binary digit (0 or 1) and hence are less than 2, we just return the number converted to a string. Otherwise we call recursively on the floor of half the number (as yours does) and append the final digit.

const binary = (n) =>
  n < 2
    ? String (n)
    : binary (Math.floor (n / 2)) + (n % 2)
    
console.log (binary(22)) //=> '10110'

console.log ([65, 66, 67] .map (binary)) //=> ['1000001', '1000010', '1000011']

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

Comments

0

In your function you have this code

var  r = temp3[i];

I don't see any temp3 variable anywhere in your code above so I'd imagine that could be causing some issues.

1 Comment

Thank you, Optiq! It was a wrong code (Updated it now). I am getting the code as above. getting correct output as below:

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.