Home Communities
IT Knowledge
Inspiration
Languages
EN

# JavaScript - convert decimal number to bin, oct, hex, etc. (to any base system)

8 points
Created by:
533

In this short article, we would like to show how to convert any decimal number to the indicated base system using JavaScript.

Quick solution:

``````// ONLINE-RUNNER:browser;

var dec = 123; // decinal number
var base = 16; // to base 16 number - to hexadecinal number

var hex = dec.toString(base);

console.log(hex);  // 7b
console.log(hex.toUpperCase());  // 7B``````

## Custom implementation

The below function is able to convert from decimal to:

• bin (binary system),
• oct (octal systems),
• hex (hexal / hexadecimal system),
• any indicated but not greater than 36 (add more characters to the alphabet to get greater base systems).

Practical example:

``````// ONLINE-RUNNER:browser;

var ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function convertBase(dec, base) { // add to ALPHABET more characters to get greater base
if (base > ALPHABET.length) {
throw new Error('Maximal supported base value is ' + ALPHABET.length + '.');
}
var result = '';
while (true) {
var quotient = Math.floor(dec / base);
var index = dec - base * quotient;
result = ALPHABET[index] + result;
if (quotient < 1) {
break;
}
dec = quotient;
}
return result;
}

// Usage example:

//                      dec  base
console.log(convertBase(  0,  2));  // 0       (base 2)   <--- bin
console.log(convertBase(123,  2));  // 1111011 (base 2)   <--- bin
console.log(convertBase(123,  3));  // 11120   (base 3)
console.log(convertBase(123,  4));  // 1323    (base 4)
console.log(convertBase(123,  5));  // 443     (base 5)
console.log(convertBase(123,  6));  // 323     (base 6)
console.log(convertBase(123,  7));  // 234     (base 7)
console.log(convertBase(123,  8));  // 173     (base 8)   <--- oct
console.log(convertBase(123, 10));  // 123     (base 10)  <--- dec / identity
console.log(convertBase(123, 16));  // 7B      (base 16)  <--- hex
console.log(convertBase(123, 32));  // 7R      (base 32)
console.log(convertBase(123, 36));  // 3F      (base 36)
console.log(convertBase( 36, 36));  // 10      (base 36)``````

## Alternative titles

Join to our subscribers to be up to date with content, news and offers.