hex string to int javascript

Hex String to Integer Conversion in JavaScript

Converting a hexadecimal string to an integer in JavaScript can be done in several ways. Here are some of the methods:

Method 1: parseInt() function with radix parameter

The simplest way is to use the built-in JavaScript function parseInt() with the radix parameter set to 16, which indicates that the input is in hexadecimal format:


const hexString = "1a";
const decimalNumber = parseInt(hexString, 16);
console.log(decimalNumber); // Output: 26
    

The above code snippet will convert the hexadecimal string "1a" into a decimal number and store it in the variable decimalNumber.

Method 2: Bitwise left shift operator

Another method is to use the bitwise left shift operator (<<) to convert each hexadecimal digit to its decimal equivalent:


const hexString = "1a";
let decimalNumber = 0;
for (let i = 0; i < hexString.length; i++) {
  const hexDigit = hexString[i];
  const decimalDigit = parseInt(hexDigit, 16);
  decimalNumber = (decimalNumber << 4) | decimalDigit;
}
console.log(decimalNumber); // Output: 26
    

The above code snippet iterates over each hexadecimal digit in the string and converts it to its decimal equivalent using the parseInt() function. Then, it shifts the previously converted digits 4 bits to the left and bitwise ORs the result with the current digit's decimal equivalent.

Method 3: Reduce function with bit shifting

Another approach is to use the reduce() function to iterate over each hexadecimal digit in the string and use bit shifting to convert it to its decimal equivalent:


const hexString = "1a";
const decimalNumber = hexString.split("")
  .reduce((acc, cur) => (acc << 4) | parseInt(cur, 16), 0);
console.log(decimalNumber); // Output: 26
    

The above code snippet splits the hexadecimal string into an array of individual digits and then uses reduce() to iterate over each digit. It uses bit shifting to convert each digit to its decimal equivalent and accumulates the result in the acc variable.

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