Skip to content
the poor coder

hex to decimal formula javascript

Poor Man
Published
Reading time
1 min read
On this page

Hex to Decimal Formula in JavaScript#

Converting hexadecimal numbers to decimal is a common task in programming. In JavaScript, there are several ways to do this conversion, but one of the simplest ways is to use the parseInt() function.

Method 1: Using parseInt() Function#

The parseInt() function takes two arguments: the string to parse and the radix (or base) of the number system being used. For hexadecimal numbers, the radix is 16. Here's an example:

Text

const hexValue = "1A";
const decimalValue = parseInt(hexValue, 16);

console.log(decimalValue); // Output: 26

Method 2: Using Number() Function#

The Number() function can also be used to convert hexadecimal numbers to decimal. However, it requires that the hexadecimal number be preceded by "0x". Here's an example:

Text

const hexValue = "1A";
const decimalValue = Number("0x" + hexValue);

console.log(decimalValue); // Output: 26

Method 3: Using Bitwise Operators#

Another way to convert hexadecimal numbers to decimal is to use bitwise operators. The "&" operator can be used to extract each digit of the hexadecimal number, and then the resulting decimal values can be added together. Here's an example:

Text

const hexValue = "1A";
let decimalValue = 0;

for (let i = 0; i < hexValue.length; i++) {
  decimalValue = (decimalValue << 4) | parseInt(hexValue.charAt(i), 16);
}

console.log(decimalValue); // Output: 26

In this example, the "<<" operator is used to shift the decimal value left by 4 bits (or one hexadecimal digit). Then the "|" operator is used to combine the shifted value with the decimal value of the current digit, which is obtained using the parseInt() function.

Conclusion#

These are some of the ways to convert hexadecimal numbers to decimal in JavaScript. The parseInt() function is the simplest and most commonly used method, but bitwise operators can also be used for more advanced scenarios.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC