0

Ok so i've got an array with integers (converted from intel Hex file), and need to output it as binary.

Here is the file reader, but how do i convert the array back to a byte stream (utf-8)?

$filename = "./latest/firmware.hex";
$file = fopen($filename, "r");
$image = array();
$imagesize = 0;
$count = 0;
$address = 0;
$type = 0;

while(!feof($file))
{
    $line = fgets($file);
    $count = intval(substr($line,1,2));
    $address = intval(substr($line,3,4));
    $type = intval(substr($line,7,2));
    if($type==0)
    {
        for ($i=0; $i < $count; $i++) { 
            $image[$address+1] = intval(substr($line,9+$i*2,2));
            if (($address + $i) > $imagesize)
            {
                $imagesize = $address + $i;
            }
        }
    }   
    else if($type == 1)
    {
        break;
    }
}
3
  • are you trying to print binary? or write an image out as binary data? your question is unclear. it looks like the latter, here, but your question makes it sound like you want print binary. Commented Sep 7, 2010 at 16:38
  • Sorry didn't clear out exactly what this is for. I'm reading an Index HEX file (compiled embedded C) that is streamed in 1k blocks to a GSM device to update the firmware. The resulting binary is pumped directly into flash on the device and rebooted once complete. Commented Sep 8, 2010 at 5:15
  • found the problem, it think... i was bing stupid. used intval() to convert the hex values instead of hexdec(). should work now. Commented Sep 8, 2010 at 6:04

1 Answer 1

2
  • Step 1: Use chr() to get character from ascii value.

  • Step 2: Use fwrite() to write binary data to file.

You may want to collect it to a buffer before writing it to file. PHP strings can contain zeroes safely.

Sign up to request clarification or add additional context in comments.

2 Comments

Additionally: simple echo() can write zero bytes to standard output. But it may have problems over 128 if you use UTF-8 as internal and/or output encoding.
I was a bit worried at first that this wasn't a UTF-8 solution but since chr() and fwrite() both treat it byte for byte you basically ignore the encoding, which means you should end up with a correct file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.