Posted By

bucabay on 09/03/09


Tagged

base hex binary dec


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

vali29
bucabay
mvrilo
waldir


Number base conversion, hex, dec, binary


 / Published in: JavaScript
 

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

The snippet uses the native Javascript function so it should be more efficient then for instance using arithmetic or looped bitwise operations etc.

Examples:

// convert the decimal 10 to hex 
Math.base(10, 16); // 'a'

// convert the hex 'a' to decimal 
Math.base('a', 10, 16); // 10

// convert the decimal 10 to binary
Math.base(10, 2); // '1010'

// convert the hex 'a' to decimal 
Math.base('a', 2, 16); // 1010

Base conversion in JavaScript

  1. Math.base = function base(n, to, from) {
  2. return parseInt(n, from || 10).toString(to);
  3. }

Report this snippet  

You need to login to post a comment.