Willian Vaz
Willian Vaz

Reputation: 11

Changing base of a number back and forth javascript

Does anyone know how to convert a number back and forth between different bases in javascript? For example:

var num = 3213;
num = parseInt(num, 15);

I converted the number to the base 15. Is there another builtin function in javaScript that converts a from a given base X to base Y and vise-versa?

Thank you for your time helping.

Upvotes: 0

Views: 176

Answers (2)

elfan
elfan

Reputation: 1131

To easily convert from one base to another, you can use this:

function baseConvert(n, from, to) {
    //example: baseConvert(11110011, 2, 16) returns f3
    return parseInt(n, from).toString(to);
}

Upvotes: 0

riteshtch
riteshtch

Reputation: 8769

numberVar.toString(radix) // to convert a number to desired base and use 
parseInt("string", inputBase) // to convert a string of numbers from given base to decimal.

> var i=5
> i.toString(2)
"101"
> parseInt("101", 2)
5
> var i=9
> i.toString(8)
"11"
> parseInt("11", 8)
9

Upvotes: 1

Related Questions