Languages
[Edit]
EN

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

0 points
Created by:
Lillie-Rose-Finnegan
489

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

Quick solution:

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

const hex: string = 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:

const ALPHABET: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

const convertBase = (dec: number, base: number): string => {
    // add to ALPHABET more characters to get greater base
    if (base > ALPHABET.length) {
        throw new Error('Maximal supported base value is ' + ALPHABET.length + '.');
    }
    let result = '';
    while (true) {
        const quotient = Math.floor(dec / base);
        const 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)

Output:

0
1111011
11120
1323
443
323
234
173
123
7B
3R
3F
10

Alternative titles

  1. TypeScript - convert dec number to bin, oct, hex, etc. (to any base system)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join