JavaScript can convert Number values to bases from 2 through 36 with toString(radix), and parse text written in another base with parseInt(text, radix).
const decimal = 255;
console.log(decimal.toString(16)); // "ff"
console.log(parseInt("ff", 16)); // 255
Decimal uses base 10, binary uses base 2, octal uses base 8, and hexadecimal uses base 16. Hexadecimal digits after 9 are represented by a through f. Web colors often use hexadecimal notation such as #0000ff.
| Decimal | Hex | Octal | Binary |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 10 |
| 3 | 3 | 3 | 11 |
| 4 | 4 | 4 | 100 |
| 5 | 5 | 5 | 101 |
| 6 | 6 | 6 | 110 |
| 7 | 7 | 7 | 111 |
| 8 | 8 | 10 | 1000 |
| 9 | 9 | 11 | 1001 |
| 10 | a | 12 | 1010 |
| 11 | b | 13 | 1011 |
| 12 | c | 14 | 1100 |
| 13 | d | 15 | 1101 |
| 14 | e | 16 | 1110 |
| 15 | f | 17 | 1111 |
| 16 | 10 | 20 | 10000 |
const n = 255;
console.log(n.toString(2)); // "11111111"
console.log(n.toString(8)); // "377"
console.log(n.toString(16)); // "ff"
console.log(parseInt("11111111", 2)); // 255
console.log(parseInt("377", 8)); // 255
console.log(parseInt("ff", 16)); // 255
See parseInt() for detailed radix rules.
console.log((35).toString(36)); // "z"A radix outside 2–36 causes Number.prototype.toString() to throw a RangeError.
console.log((-15).toString(2)); // "-1111"This is a signed textual representation, not a two's-complement bit pattern.
const value = parseInt("102", 2);
console.log(value); // 2 because parsing stops before the invalid digit 2If you require the entire input to be valid for a base, validate the string before parsing instead of relying only on parseInt().
These conversions return ordinary JavaScript Numbers, so values beyond the safe-integer range can lose integer precision. Use BigInt when an exact very large integer is required and the surrounding application supports it.
Continue with the dedicated decimal to hexadecimal and hexadecimal to decimal tutorial.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.