Javascript Function to Convert Hex String to ASCII Characters (Hexadecimal)


Given a string contains hex characters (group by two) we can convert to ASCII characters using the following Javascript Function (takes two characters and convert to decimal and then obtain its ASCII character):

1
2
3
4
5
6
7
function hexify(s) {
    let r = [];
    for (let i = 0; i < s.length - 1; i += 2) {
        r.push(String.fromCharCode(parseInt(s.charAt(i) + s.charAt(i + 1), 16)));
    }
    return r.join("");
}
function hexify(s) {
    let r = [];
    for (let i = 0; i < s.length - 1; i += 2) {
        r.push(String.fromCharCode(parseInt(s.charAt(i) + s.charAt(i + 1), 16)));
    }
    return r.join("");
}

For example:

1
2
// the following returns "REVERT opcode executed"
hexify("524556455254206f70636f6465206578656375746564");
// the following returns "REVERT opcode executed"
hexify("524556455254206f70636f6465206578656375746564");

The above function has been integrated into a Serverless API based on CloudFlare Worker, see below API call:

1
curl -s -X POST --data "524556455254206f70636f6465206578656375746564" "https://str.justyy.workers.dev/hex"
curl -s -X POST --data "524556455254206f70636f6465206578656375746564" "https://str.justyy.workers.dev/hex"

You can pass parameter string as GET e.g.

1
curl -s -X GET "https://str.justyy.workers.dev/hex/?s=524556455254206f70636f6465206578656375746564"
curl -s -X GET "https://str.justyy.workers.dev/hex/?s=524556455254206f70636f6465206578656375746564"

There is a simple way from the BASH command. We can actually pipe the input using xxd:

1
echo "524556455254206f70636f6465206578656375746564" | xxd -ps -r
echo "524556455254206f70636f6465206578656375746564" | xxd -ps -r

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
270 words
Last Post: Teaching Kids Programming - Longest Even Value Path in Binary Tree via Graph Breadth First Search Algorithm
Next Post: Teaching Kids Programming - Longest Path in Binary Tree via Recursive Depth First Search Algorithm

The Permanent URL is: Javascript Function to Convert Hex String to ASCII Characters (Hexadecimal) (AMP Version)

Leave a Reply