Thursday 30 May 2013

Hex2Str and Str2Hex Javascript Functions

Today I needed some Javascript to convert a HEX-encoded string to an ASCII-encoded string. The reason is that to be able to send all possible strings via AJAX-calls back to the client, without problems with quotes, apostrophes and other non-ASCII7 characters, I decided to encode the AJAX-data to hex, which is a nice and simple ASCII7 string of only the characters 0 through 9 and A through F.

After Googling a bit I found an example on webdeveloper.com and some tips on stackoverflow.com, and both combined with some of my own JS-knowledge, I came up with the following small and handy functions:

function Str2Hex(tmp) {
var str = "";
for (var i=0; i<tmp.length; i++)
str += ("00" + (tmp.charCodeAt(i)).toString(16)).substr(-2);
return(str);
}
function Hex2Str(tmp) {
var str = "";
for (var i=0; i<tmp.length; i+=2)
str += String.fromCharCode(parseInt(tmp.substr(i,2),16));
return(str);
}

For example, after a user made a selection from the autocomplete menu and you return a HEX-encoded string containing multiple values, separated by "+++", to fill other form-fields too:

..., select: function(e,u) {
var x = Hex2Str(u.item.value).split("+++");
$("#field1").val(x[0]).change();
$("#field2").val(x[1]).change();
... etc.
return false; } ....

Or when you return multiple values as a HEX-encoded JSON array:

..., select: function(e,u) {
var x = u.item.value;
$("#field1").val(Hex2Str(x.field1)).change();
$("#field2").val(Hex2Str(x.field2)).change();
... etc.
return false; } ....

Happy coding!