How do I implement hex2bin()?

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

    With reference to node.js ( not in browser ).

    Basically it's all over-engineered and does not work well.

    responses are out of alignment and though text-wise they are the same bit wise everything is all over the place :

    curl http://phpimpl.domain.com/testhex.php | xxd
    
    00000000: de56 a735 4739 c01d f2dc e14b ba30 8af0  .Q.%G9.....;.0..
    
    curl http://nodejs.domain.com/ | xxd
    
    00000000: c39e 56c2 a725 4739 c380 c3ad c3b1 c39c  ..Q..%G9........
    00000010: c3a1 37c2 6b30 c28f c3b0                 ..;..0....
    

    The proper way to implement this in node is :

    function hex2bin(hex){
       return new Buffer(hex,"hex");
    }
    
    
    curl http://nodejs.domain.com/ | xxd
    
    00000000: de56 a735 4739 c01d f2dc e14b ba30 8af0  .Q.%G9.....;.0..
    

    Hope this helps.

    0 讨论(0)
  • 2020-11-29 03:28

    JavaScript doesn't have support for binary data. Nevertheless you can emulate this with regular strings.

    var hex = "375771", // ASCII HEX: 37="7", 57="W", 71="q"
        bytes = [],
        str;
    
    for(var i=0; i< hex.length-1; i+=2){
        bytes.push(parseInt(hex.substr(i, 2), 16));
    }
    
    str = String.fromCharCode.apply(String, bytes);
    
    alert(str); // 7Wq
    
    0 讨论(0)
  • 2020-11-29 03:30

    If someone needs the other direction (bin to hex), here is it:

    function bin2hex(bin) {
        return new Buffer(bin).toString("hex");
    }
    
    0 讨论(0)
  • 2020-11-29 03:32
    function hex2bin(hex)
    {
        var bytes = [], str;
    
        for(var i=0; i< hex.length-1; i+=2)
            bytes.push(parseInt(hex.substr(i, 2), 16));
    
        return String.fromCharCode.apply(String, bytes);    
    }
    

    thanks to Andris!


    Other useful information about this topic (dex2bin,bin2dec) can be found here. According to that, here is a bin2hex solution:

    parseInt(1100,2).toString(16); //--> c
    
    0 讨论(0)
  • 2020-11-29 03:37

    JavaScript does actually contain support for binary data. See Uint8Array.

    Just read each byte from the array and convert it into hexadecimal.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题