Base Conversion


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

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


Copy this code and paste it in your HTML
  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

You need to login to post a comment.