How do I implement hex2bin()?

后端 未结 8 1830
野趣味
野趣味 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:46

    Although not an answer to the actual question, it is perhaps useful in this case to also know how to reverse the process:

    function bin2hex (bin)
    {
    
      var i = 0, l = bin.length, chr, hex = ''
    
      for (i; i < l; ++i)
      {
    
        chr = bin.charCodeAt(i).toString(16)
    
        hex += chr.length < 2 ? '0' + chr : chr
    
      }
    
      return hex
    
    }
    

    As an example, using hex2bin on b637eb9146e84cb79f6d981ac9463de1 returns ¶7ëFèL·mÉF=á, and then passing this to bin2hex returns b637eb9146e84cb79f6d981ac9463de1.

    It might also be useful to prototype these functions to the String object:

    String.prototype.hex2bin = function ()
    {
    
      var i = 0, l = this.length - 1, bytes = []
    
      for (i; i < l; i += 2)
      {
        bytes.push(parseInt(this.substr(i, 2), 16))
      }
    
      return String.fromCharCode.apply(String, bytes)   
    
    }
    
    String.prototype.bin2hex = function ()
    {
    
      var i = 0, l = this.length, chr, hex = ''
    
      for (i; i < l; ++i)
      {
    
        chr = this.charCodeAt(i).toString(16)
    
        hex += chr.length < 2 ? '0' + chr : chr
    
      }
    
      return hex
    
    }
    
    alert('b637eb9146e84cb79f6d981ac9463de1'.hex2bin().bin2hex())
    

提交回复
热议问题