/* decimal to other base (binary or hexadecimal) function*/
function decimaltobase(num, base) {
var number = num;
var basestring = "";
var baseToString = "";
while (number > 0)
{
var b = number % base;
var quotient = number / base;
baseToString = toString(b); /* put bit to the left of any previous bits in the bitstring*/
basestring = baseToString + basestring;
number = quotient;
}
alert(num + " to base " + base + " is : " + basestring); /*although in Chrome developer tools i use console.log()*/
}
/* in the decimaltobase function call, second parameter is base converting to*/
decimaltobase(15, 2);
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
Note: Backticks are not single quotes.
1 Like
I think you need to rethink how you breaking that number apart.
1 Like
Can number ever be 0? You may want to follow how your variables changes at each step. Use a lot of console.log()
there if you can, or just go with pen and paper
1 Like
Thank you for showing me that! I will use that next time.