1

I have to extract some data from a binary file. the data begin with a hex marker. I have first to find this marker and then extract the x bytes after.

PHP is good for text file manipulation.

Someone have a good idea to do that with binary data ?

Thanks !

1
  • Try unpack() Commented Jan 15, 2012 at 19:26

2 Answers 2

3

You don't need any special functions like pack or unpack etc...although pack may be useful for specifying the needle to search for. php doesn't apply any character encoding to strings, it leaves them as is, so it's binary friendly by default.

$hexMarker = 0x70000000;// or whatever
$binaryData = file_get_contents($filename);
$x = 5;
$pos = strpos($binaryData, $hexMarker);
if ($pos !== false) {
    $start = $pos + strlen($hexMarker);
    echo substr($binaryData, $start, $x);
}

you may consider using fopen and fread in an iterative fashion if the size of the file is large, as file_get_contents would consume a lot of memory in that case. But that's a separate question anyway.

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

Comments

3

You should look at the unpack() and pack() functions.

Here are a sample that reads a entire file into a buffer and uses unpack() to get the values of the two first chars:

$fp = fopen("binary.txt", "r");
fseek($fp, 0, SEEK_END);
$fs = ftell($fp);
fseek($fp, 0, SEEK_SET);
$binary = fread($fp, $fs);
fclose($fp);
$unpacked = unpack("c2", $binary);

Comments

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.