Re: upapck() woes
| From: | Tom Rogers | Date: | Thu, 02 Oct 2003 01:17:43 +0000 |
| Subject: | Re: upapck() woes | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-164652@lists.php.net to get a copy of this message | ||
Hi,
Thursday, October 2, 2003, 3:31:40 AM, you wrote:
JB> I have kibitzed and kaboodles all morning seeking the answer to the
JB> unpack question. I need to unpack some binary data and make sense of it.
JB> Unfortunately I am unsure how the binary for this was created. I have
JB> tried converting ascii but I am thinking (after much frustration) that I
JB> should go hex and then convert that. Has anyone had any experience in
JB> unpacking unknown binaries and making sense of them?
JB> TVMIA!
JB> --
JB> PHP General Mailing List (http://www.php.net/)
JB> To unsubscribe, visit: http://www.php.net/unsub.php
Have you tried using the unpack() function ?
If you need to dump the data to see what it looks like here is a couple of
functions that will help.
function hexDumpChar($str,$len){
//echo 'Len '.strlen($str);
$strlen = strlen($str);
for($z=0;$z < $strlen;$z+=$len){
$left = $strlen - $z;
$jlen = ($left > $len)? $len:$left;
for($j=$z;$j<$z+$jlen;$j++){
printf(" %02x",ord($str[$j]));
}
echo ' ';
for($j=$z;$j<$z+$jlen;$j++){
printf(" %c",ord($str[$j]));
}
echo '<br>';
}
echo '<br>';
}
function hexDumpWord($str,$len){
//little endian;
for($z=0,$y=strlen($str);$z < $y;$z+=$len){
for($j=$z;$j<$z+$len;$j+=2){
printf(" %02x%02x ",ord($str[$j+1]),ord($str[$j]));
}
echo '<br>';
}
echo '<br>';
}
function hexDumpDoubleWord($str,$len){
//little endian;
for($z=0,$y=strlen($str);$z < $y;$z+=$len){
for($j=$z;$j<$z+$len;$j+=4){
printf("
%02x%02x%02x%02x ",ord($str[$j+3]),ord($str[$j+2]),ord($str[$j+1]),ord($str[$j]));
}
echo '<br>';
}
echo '<br>';
}
to use
$str = substr($binary_data,0 256);
hexDumpChar($str,16);
will dump the first 256 bytes of data with 16 chars per line.
If the binary data is little endian and you need to extract a 2 words (word = 2
bytes) you can do something like this:
$ptr = 0;
$word1 = (ord($binary_data[$ptr+1]) << 8) | ord($binary_data[$ptr]);
$ptr +=2;
$word2 = (ord($binary_data[$ptr+1]) << 8) | ord($binary_data[$ptr]);
or
$str = substr($binary_data,0,2);
$up = unpack("vword1/vword2",$str);
will give you an array
$up['word1'] and $up['word2'];
If you don't know the format of the original data it can be a long process
undoing it :)
--
regards,
Tom