In my Client/Server application I'm getting from the server, string in Hex format which I need to convert to UTF8. Then after some manipulation I need to encode the string back, from UTF8 to Hex and return in to the server.
I've built this function to parse the Hex string to UTF8. However when I try to reverse this algorithm I'm getting something completely else.
Here is my test:
function hexToUtf8(s)
{
return decodeURIComponent(
s.replace(/\s+/g, '') // remove spaces
.replace(/[0-9a-f]{2}/g, '%$&') // add '%' before each 2 characters
);
}
function utf8ToHex(s)
{
return encodeURIComponent(s).replace(/%/g, ""); // remove all '%' characters
}
var hex = "52656c6179204f4e214f706572617465642062792030353232";
var utf8 = hexToUtf8(hex); // result: "Relay ON!Operated by 0522" (correct value)
var hex2 = utf8ToHex(utf8); // result: "Relay20ON!Operated20by200522" (some junk)
console.log("Hex: " + hex);
console.log("UTF8: " + utf8);
console.log("Hex2: " + hex2);
console.log("Is conversion OK: " + (hex == hex2)); // false