PDA

View Full Version : Unpack multiple data structures


buzzwogger
02-27-2007, 11:09 AM
I have a hex memory dump which looks like this

1de00034 00000109,744ea6d6,00020020,81800005 ....tN..........
1de00044 00030004,00040000,00020002,0000ffff ................
1de00054 00101194,ffffffff,ffffffff,ffffffff ................

I unpack and get rid of the commas so now my data looks like this

00000109744ea6d600020020818000050003000400040000000200020000ffff00101194ffffffffffffffffffffffff

I now want to loop through the data and retrieve n data structures (ts[n], id[n], value[n]), however I only seem to be able to get the first structure. while(<OUT>) this seemed to work for looping trough to extract data and getting rid of the address and “tail”… So any help would be brilliant!

sub decode
{
my ($outfile) = @_;
open OUT, "<$outfile" or die "Can't open $outfile: $!\n";

$template = "A8 A2 A46";
while(<OUT>)
{
my($hex_data) = $_;
($ts,$id,$value)=unpack($template,$hex_data);
printf($ts);
}
}

buzzwogger
03-01-2007, 11:57 AM
Bit of a convoluted way but this works... I split my string up into array[n], where value 'n' was the size of my template

$template = "A8 A2 A46";
#size of template
my $value_count = length pack($template, $data_ );
#size of data string
my $data_size = length($data_);
#how many structs in string
my $structure_count = ($data_size / $value_count);
$count=0;
while($count<=$structure_count)
{
to unpack the string in bytes struct
$shift_count1 = $value_count * $count;
print "shift count 1 = " . $shift_count1 . "\n";
if ($count==0){
$shift_count2 = $value_count - 1;
print "shift count 2 = " . $shift_count2 . "\n";
}
else{
$shift_count2 = (2 * $shift_count1) - 1;
print "shift count 2 = " . $shift_count2 . "\n";
}

$data_sections= join("", (split(//,$data_))[$shift_count1..$shift_count2]);
($ts[$count], $id[$count], $val[$count])=unpack($template,$data_sections);
}