Covenvert Hex to binary

Good morning,
Ive got a PHP script which needs to accept a binary file in HEX, and write it to disc, is there an easy and quick process for converting HEX to a byte and then writing it to a file?

The file is passed through to the PHP script through $_POST['fileContents'], and looks like:-
               C0-F2-0C-80-60-EE-53-82-39-3C-93-57-1B-A7-66-44-AD-25-7B-6A

So I suppose first thing I need to do is split the string into individual bytes and then convert each hex number to its binary and then write that to disc, but my attached code isnt the quickest in the world, is there a way I can speed it up?
<?php
$hexArray = explode("-", $_POST['fileContent']);
$write2Disc = ""

foreach ($hexArray as $hexElement)
	{
	$write2Disc = $write2Disc . chr(hexdec($hexElement));
	}

$myFile = "testFile.jpg";
$fh = fopen($myFile, 'a');
fwrite($fh, $write2Disc);
fclose($fh);
?>

Open in new window

tonelm54Asked:
Who is Participating?
 
shanikawmConnect With a Mentor Commented:
Try this.

$write2Disc = pack("H*",preg_replace('/-/','',$_POST['fileContent']))

Open in new window

0
 
jet-blackCommented:
You can use decbin() function to convert decimal to binary:
http://www.php.net/manual/en/function.decbin.php
0
All Courses

From novice to tech pro — start learning today.