Skip to content
the poor coder

hex string to int javascript

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

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:

Text

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:

Text

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.

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