How do I implement hex2bin()?

后端 未结 8 1841
野趣味
野趣味 2020-11-29 02:40

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()

8条回答
  •  孤城傲影
    2020-11-29 03:38

    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"
    

提交回复
热议问题