Hi,

I need to convert a file from its binary form to a hex representation.

A working PERL version of this is as follows:

perl version

open(F, "myimage.gif") || die $!;
binmode(F);
$s = $hx = "";
while (read(F, $s, 1) > 0) {
$hx .= sprintf("%02X", ord($s));
}
close F;
print "The hex-encoded GIF file is: $hx\n";

I have tried to make a PHP version, which goes like this:

my php version

$fp = fopen("test.gif","r") or die("No such gif");
while (!feof($fp)) {
$line = fgets($fp,1024);
$lines.=$line;
}
fclose($fp);

$img=bin2hex($lines);

echo "img is ".$img."\n<br>";

The result I get is:
47494638396148d848eab4d463f556e3d7eafa50

But this doesn't seem right, as I'm expecting a HEX string which is 328 characters long for this file.

Anyone got any idea how to do this? Or is there something obvious I'm missing?

Thanks in advance

Anthony

    Hey Anothony:

    The problem with your code is that fgets reads a STRING, so if there are any null characters in the gif file (which is common for binary files) it see it as the end of the string or file. You need to use fread():

    http://www.php.net/fread

    try:

    $filename = "test.gif";

    // Turn on the b flag to be cross-platform (i.e. for windows)
    $fp = fopen($filename, "rb");
    $image_bin = fread($fp, filesize($filename));
    fclose($fp);

    $image_hex = bin2hex($image_bin);

    Now, $image_hex should have what you are looking for! Hope that helps.

    Chris King

      hi,

      yeah, done that and it seems to be what i'm looking for.

      many thanks!

      anthony

        Write a Reply...