Ad space (banner)
🟨JavaScript Lessons
Lesson 63 / 69

Converting Number Bases (Binary and Hexadecimal)

In this lesson you'll learn how to convert numbers to binary and hexadecimal in JavaScript, so you can understand the basic idea behind base conversion. This is for people searching "JavaScript base conversion" or "JavaScript toString hexadecimal."

Number.toString(base) converts a number into a string in a specified base. Conversely, parseInt(string, base) converts a string in that base back into a base-10 number. A base is a number representing "what counts as one unit at each digit" — base 10 is 10, binary is 2, and hexadecimal is 16.

The sample code converts the number 42 into a binary string with .toString(2), and into a hexadecimal string with .toString(16). Conversely, parseInt("101010", 2) converts the binary string "101010" back into the base-10 number 42, letting you confirm the conversion was done correctly.

A common beginner stumbling block is forgetting to specify the second argument (the base) for parseInt(). Omitting the base causes it to be interpreted as base 10, so you must always specify the base to correctly convert a binary or hexadecimal string. Understanding this idea of base conversion also deepens your understanding of what's going on inside a computer.

Since binary is commonly used inside a computer, and hexadecimal for things like color codes, this idea of base conversion is generally useful basic knowledge across all of programming. A CSS color specification like #FF0000 is also written in hexadecimal, so this knowledge comes into play throughout web development.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)