Reputation: 389
I'm trying to write a binary file from hex string.
For example, if my hex string is C27EF0EC
, then the hex file should contain ASCII characters for C2
, 7E
, F0
and EC
.
How do I do this in PHP
?
Here's what I've tried:
$s="";
for ($i=0; $i<count($h); $i++) {
$s+=pack("C*", "0x".$h[$i]);
}
$f2=fopen("codes0", "wb+");
fwrite($f2, $s);
Upvotes: 4
Views: 3186
Reputation: 21851
Assuming that array $binary
is a previously constructed array bytes (like monochrome bitmap pixels in my case) that you want written to the disk in this exact order, the below code worked for me on an AMD 1055t running ubuntu server 10.04 LTS.
I iterated over every kind of answer I could find on the Net, checking the output (I used either shed or vi, like in this answer) to confirm the results.
<?php
$fp = fopen($base.".bin", "w");
$binout=Array();
for($idx=0; $idx < $stop; $idx=$idx+2 ){
if( array_key_exists($idx,$binary) )
fwrite($fp,pack( "n", $binary[$idx]<<8 | $binary[$idx+1]));
else {
echo "index $idx not found in array \$binary[], wtf?\n";
}
}
fclose($fp);
echo "Filename $base.bin had ".filesize($base.".bin")." bytes written\n";
?>
Upvotes: 0
Reputation: 95252
So the first thing you need to do is turn your single string into an array of two-character strings with str_split
.
$hex_bytes = str_split($h, 2);
Then you want to convert each of those values from a hexadecimal string to the corresponding number with hexdec
.
$code_array = array_map(hexdec, $hex_bytes);
Then you want the byte value corresponding to each of those character codes, which you can get with chr
:
$char_array = array_map(chr, $code_array);
Finally, you want to join all those bytes together into a single string, which you can do with implode
.
$s = implode($char_array);
You can use the steps above in that order, or you can put it all together into one expression like this:
$s = implode(array_map(chr, array_map(hexdec, str_split($h,2))));
Note that as soon as you get a value above 0x7F it's no longer "ASCII".
Upvotes: 2