Home > Web Front-end > JS Tutorial > How Do I Convert Between Decimal and Hexadecimal in JavaScript?

How Do I Convert Between Decimal and Hexadecimal in JavaScript?

Mary-Kate Olsen
Release: 2024-12-11 13:59:24
Original
199 people have browsed it

How Do I Convert Between Decimal and Hexadecimal in JavaScript?

Decimal to Hexadecimal Conversion in JavaScript

Converting decimal values to hexadecimal equivalents is a common task in programming. In JavaScript, this can be done with ease using the toString(base) method.

Conversion to Hexadecimal String

To convert a decimal number to its hexadecimal string representation, use the following syntax:

hexString = yourNumber.toString(16);
Copy after login

For example, to convert the decimal number 10 into hexadecimal, we would write:

let hexString = 10.toString(16);
Copy after login

This will assign the string "a" to the hexString variable, as "a" is the hexadecimal representation of 10.

Conversion from Hexadecimal String

To convert a hexadecimal string back to its decimal equivalent, use the parseInt(string, base) function:

yourNumber = parseInt(hexString, 16);
Copy after login

For example, to convert the hexadecimal string "a" to its decimal equivalent, we would write:

let yourNumber = parseInt("a", 16);
Copy after login

This will assign the value 10 to the yourNumber variable.

Remember that the base parameter in both methods specifies the base of the number being converted. For hexadecimal, always set the base to 16.

The above is the detailed content of How Do I Convert Between Decimal and Hexadecimal in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template