w3resource

JavaScript: Convert Hexadecimal to ASCII format

JavaScript String : Exercise-28 with Solution

Write a JavaScript function to convert Hexadecimal to ASCII format.

Test Data:
console.log(hex_to_ascii('3132'));
console.log(hex_to_ascii('313030'));
Output:
"12"
"100"

Sample Solution:

JavaScript Code:

// Function to convert a hexadecimal string to its ASCII representation
function hex_to_ascii(str1) {
    // Convert the input hexadecimal string to a regular string
    var hex = str1.toString();
    // Initialize an empty string to store the resulting ASCII characters
    var str = '';
    // Iterate through the hexadecimal string, processing two characters at a time
    for (var n = 0; n < hex.length; n += 2) {
        // Extract two characters from the hexadecimal string and convert them to their ASCII equivalent
        str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
    }
    // Return the resulting ASCII string
    return str;
}
// Example usage of the hex_to_ascii function
console.log(hex_to_ascii('3132'));   // Output: '12'
console.log(hex_to_ascii('313030')); // Output: '100'

Output:

12
100

Explanation:

In the exercise above,

The "hex_to_ascii()" function takes a hexadecimal string 'str1' as input and converts it into its corresponding ASCII representation. Here's a breakdown of each part:

  • var hex = str1.toString();: Convert the input hexadecimal string to a regular string and store it in the variable 'hex'.
  • var str = '';: Initialize an empty string 'str' which stores the resulting ASCII characters.
  • for (var n = 0; n < hex.length; n += 2) {: Iterate through the hexadecimal string in steps of 2 characters.
  • str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));: Extract two characters from the hexadecimal string starting at index n, convert them to their decimal equivalent using 'parseInt', and then convert the decimal value to its corresponding ASCII character using 'String.fromCharCode()'. Append this ASCII character to the 'str' string.
  • return str;: Return the resulting ASCII string.

Flowchart:

Flowchart: JavaScript- Convert Hexadecimal to ASCII format

Live Demo:

See the Pen JavaScript Convert Hexadecimal to ASCII format - string-ex-28 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to convert ASCII to Hexadecimal format.
Next: Write a JavaScript function to find a word within a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-string-exercise-28.php