EN
TypeScript - convert decimal number to bin, oct, hex, etc. (to any base system)
0 points
In this short article, we would like to show how to convert any decimal number to the indicated base system using TypeScript.
Quick solution:
xxxxxxxxxx
1
const dec: number = 123; // decinal number
2
const base: number = 16; // to base 16 number - to hexadecinal number
3
4
const hex: string = dec.toString(base);
5
6
console.log(hex); // 7b
7
console.log(hex.toUpperCase()); // 7B
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:
xxxxxxxxxx
1
const ALPHABET: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
2
3
const convertBase = (dec: number, base: number): string => {
4
// add to ALPHABET more characters to get greater base
5
if (base > ALPHABET.length) {
6
throw new Error('Maximal supported base value is ' + ALPHABET.length + '.');
7
}
8
let result = '';
9
while (true) {
10
const quotient = Math.floor(dec / base);
11
const index = dec - base * quotient;
12
result = ALPHABET[index] + result;
13
if (quotient < 1) {
14
break;
15
}
16
dec = quotient;
17
}
18
return result;
19
};
20
21
22
// Usage example:
23
24
// dec base
25
console.log(convertBase( 0, 2)); // 0 (base 2) <--- bin
26
console.log(convertBase(123, 2)); // 1111011 (base 2) <--- bin
27
console.log(convertBase(123, 3)); // 11120 (base 3)
28
console.log(convertBase(123, 4)); // 1323 (base 4)
29
console.log(convertBase(123, 5)); // 443 (base 5)
30
console.log(convertBase(123, 6)); // 323 (base 6)
31
console.log(convertBase(123, 7)); // 234 (base 7)
32
console.log(convertBase(123, 8)); // 173 (base 8) <--- oct
33
console.log(convertBase(123, 10)); // 123 (base 10) <--- dec / identity
34
console.log(convertBase(123, 16)); // 7B (base 16) <--- hex
35
console.log(convertBase(123, 32)); // 7R (base 32)
36
console.log(convertBase(123, 36)); // 3F (base 36)
37
console.log(convertBase( 36, 36)); // 10 (base 36)
Output:
xxxxxxxxxx
1
0
2
1111011
3
11120
4
1323
5
443
6
323
7
234
8
173
9
123
10
7B
11
3R
12
3F
13
10