Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement hex2bin()?

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() and json_encode() on PHP side.

How do I convert the hexadecimal string in binary string, with JavaScript?

like image 867
Martin Vseticka Avatar asked Oct 08 '11 07:10

Martin Vseticka


People also ask

What is bin2hex?

The bin2hex() function converts a string of ASCII characters to hexadecimal values. The string can be converted back using the pack() function.


1 Answers

To answer your question:

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

Here are some further functions you may find useful for working with binary data:

//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)} 
like image 151
tobspr Avatar answered Sep 28 '22 03:09

tobspr