2011-10-08 12 views
19

Ho bisogno di comunicare tra Javascript e PHP (io uso jquery per ajax) ma l'output dello script PHP può contenere dati binari. Ecco perché uso la funzione bin2hex in PHP. Quindi json_encode viene applicato sul lato PHP. Quello che non so è come convertire la stringa esadecimale in dati binari sul lato Javascript.Come programmare hex2bin in Javascript?

Grazie!

+2

@MartyIX: Ecco una [funzione JavaScript con licenza BSD] (http://freebeer.smithii.com/www/_source.php?file=%2Fhome%2Fross%2Fpublic_html%2Ffreebeer%2Fwww%2Flib%2Fbin2hex. js) fa quello che vuoi. –

+0

Andres Rifrio: Grazie! –

risposta

13

JavaScript non supporta i dati binari. Tuttavia è possibile emularlo con stringhe regolari.

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 
8
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);  
} 

grazie a Andris!


Altre informazioni utili su questo argomento (dex2bin, BIN2DEC) può essere trovato here. Secondo tale, qui è una soluzione bin2hex:

parseInt(1100,2).toString(16); //--> c 
46

Per rispondere alla tua domanda:

function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)} 

Ecco alcune altre funzioni si possono trovare utili per lavorare con dati binari:

//Useful Functions 
function checkBin(n){return/^[01]{1,64}$/.test(n)} 
function checkDec(n){return/^[0-9]{1,64}$/.test(n)} 
function checkHex(n){return/^[0-9A-Fa-f]{1,64}$/.test(n)} 
function pad(s,z){s=""+s;return s.length<z?pad("0"+s,z):s} 
function unpad(s){s=""+s;return s.replace(/^0+/,'')} 

//Decimal operations 
function Dec2Bin(n){if(!checkDec(n)||n<0)return 0;return n.toString(2)} 
function Dec2Hex(n){if(!checkDec(n)||n<0)return 0;return n.toString(16)} 

//Binary Operations 
function Bin2Dec(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(10)} 
function Bin2Hex(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(16)} 

//Hexadecimal Operations 
function Hex2Bin(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(2)} 
function Hex2Dec(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(10)} 
+1

Questo non sembra funzionare con dati binari reali, piuttosto con rappresentazioni ASCII di dati binari. – Michael

+1

Le tue funzioni sono sbagliate. Almeno 'Hex2Bin' e' Bin2Hex'. Non ho nemmeno provato altro dopo ho ottenuto risultati sbagliati con quei due. Prova "Hex2Bin' =>' Bin2Hex' – Green

+0

Utilizzo questo set da molto tempo. E sto iniziando a usare Hex2Bin e l'ho realizzato proprio ora. Hex2Bin è rotto. Penso che anche Bin2Hex sia sbagliato. – huggie

3

Anche se non è una risposta alla domanda effettiva, è forse utile in questo caso anche sapere come invertire il processo:

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 

} 

A titolo di esempio, utilizzando hex2bin su b637eb9146e84cb79f6d981ac9463de1 rendimenti ¶7ëFèL·mÉF=á, e poi passando questo a bin2hex restituisce b637eb9146e84cb79f6d981ac9463de1.

Potrebbe anche essere utile al prototipo queste funzioni all'oggetto String:

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

bin2hex sembra davvero inefficiente (e lento) se voglio, per esempio, convertire un grande file immagine in una stringa esadecimale ... – Michael

3

Tutte le soluzioni proposte utilizzano String.fromCharCode, perché non semplicemente utilizzando 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); 
} 

e poi:

alert("68656c6c6f".hex2bin()); //shows "hello" 
+0

* perché non usare semplicemente unescape * - Solo perché è deprecato. ;) – yckart

+0

puoi usare decodeURIComponent invece di unescape e questo è perfetto. Comunque grazie a @Marco, ho usato la tua soluzione –

1

Con riferimento alla node.js (non nel browser).

Fondamentalmente è tutto ingegnerizzato e non funziona bene.

le risposte sono fuori allineamento e anche se il testo-saggio sono la stessa po 'saggio tutto è tutto il luogo:

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.... 

Il modo corretto per implementare questo in nodo è:

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.. 

Spero che questo aiuti.

Problemi correlati