I need to communicate between Javascript and PHP (I use jQuery for AJAX), but the output of the PHP script may contain binary data. That\'s why I use bin2hex()
All proposed solutions use String.fromCharCode, why not simply using unescape?
String.prototype.hex2bin = function()
{
var i = 0, len = this.length, result = "";
//Converting the hex string into an escaped string, so if the hex string is "a2b320", it will become "%a2%b3%20"
for(; i < len; i+=2)
result += '%' + this.substr(i, 2);
return unescape(result);
}
and then:
alert( "68656c6c6f".hex2bin() ); //shows "hello"