Posted By

Zikes on 06/30/06


Tagged

javascript numbers base hex octal decimal


Versions (?)

Base Conversion


 / Published in: JavaScript
 

This is a quick & easy system for changing the base of any number.

  1. // Sample usage for decimal to hex: base(255, '0123456789ABCDEF') == 'FF'
  2. // Common conversions such as above are easy to wrap with a helper function to speed use
  3. function base(dec,base){
  4. var len=base.length;
  5. var ret='';
  6. while(dec>0){
  7. ret = base.charAt(dec%len) + ret;
  8. dec = Math.floor(dec/len);
  9. }
  10. return ret;
  11. }
  12.  
  13. // Converts from nondecimal string to decimal
  14. // Example: unbase('FF', '0123456789ABCDEF') == 255
  15. function unbase(num, base){
  16. var len=base.length;
  17. var ret=0;
  18. for(var x=1;num.length>0;x*=len){
  19. ret += base.indexOf(num.charAt(num.length-1)) * x
  20. num = num.substr(0,num.length-1);
  21. }
  22. return ret;
  23. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: bucabay on September 3, 2009

You can use Object.prototype.toString() and parseInt() to convert bases:

eg:

// convert base 10 to 16 (dec to hex)
parseInt(10, 10).toString(16);

 // convert base 16 to 10
parseInt('a', 16).toString(10)

or a generic function:

function base(n, to, from) {
    return parseInt(n, from || 10).toString(to);
}

ref: http://www.bucabay.com/web-development/base-conversion-in-javascript/

Posted By: bucabay on September 3, 2009

The above is referenced from: [Base conversion in JavaScript][1]

You need to login to post a comment.