Number Base Conversion


/ Published in: JavaScript
Save to your folder(s)

Convert a number to a different base.


Copy this code and paste it in your HTML
  1. //Convert a number to a different base (e.g., from hex to decimal)
  2. function changeBase(num, from, to)
  3. {
  4. if(isNaN(from) || from < 2 || from > 36 || isNaN(to) || to < 2 || to > 36)
  5. throw (new RangeError("Illegal radix. Radices must be integers between 2 and 36, inclusive."));
  6. num = parseInt(num, from); //convert to decimal
  7. num = num.toString(to); //convert the decimal to desired base
  8. return num.toUpperCase();
  9. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.