hex to decimal formula javascript

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:


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:


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:


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe