Unpack binary file with C Struct to text?

R

RT

Hello,

Hope someone can help me with this question.

I have this binary file (octal dump below):

0000000 0027 c08c 0000 0404 002c 8ce0 0000 0000
0000020 4047 a06c 000b 789d
0000030

It consists of a C structure of

struct {
unsigned int where;
std::string info;
clock_t clock;
timeval time;
}

# BELOW IS THE SNIP OF MY SCRIPT. PLEASE IGNORE THE SYNTAX.

#!/usr/local/bin/perl -w

my $data_file = 'test.bin';
open INFILE, "<$data_file" or die "Unable to open \"$data_file\"\n";
binmode INFILE;

@data = ReadData ($data_file);

sub ReadData
{
my $binary;

if (!(sysread (INFILE, $binary, 24))) { return (); }

# HOW TO UNPACK THE FILE? I KNOW THE TEMPLATE BELOW IS WRONG
return (unpack ("LLLLLL", $binary));

}

My question is how do I unpack the string in the binary file and
display the output? I have read the PACK/UNPACK Perldoc but still
couldn't understand. I would really appreciate your input.

Please response to the group.

Thanks in advance!
-ryan-
 
P

Peter A. Krupa

Your main problem here isn't Perl: you can't unpack the string (i.e.,
".info") because what you have is a reference to the string class
instance, not the string itself.

You can, however unpack ".where" as an unsigned int:

perl -e "$x=\"\x00\x27\xc0\x8c\";$l=unpack('I',$x);print $l"
2361403136

Or, conversely, as a signed int:

perl -e "$x=\"\x00\x27\xc0\x8c\";$l=unpack('i',$x);print $l"
-1933564160

If you ~did~ have an ASCII string in binary data, here's how you'd print
it out:

perl -e "$x=\"\x4a\x75\x73\x74\x20\x61\x6e\x6f\x74\x68\x65\x72\x20\x50\x65\x
72\x6c\x20\x68\x61\x63\x6b\x65\x72\x2e\";print(unpack('a*',$x))"
Just another Perl hacker.
 
R

RT

Peter A. Krupa said:
Your main problem here isn't Perl: you can't unpack the string (i.e.,
".info") because what you have is a reference to the string class
instance, not the string itself.

That's what I thought. So, is that mean I cannot translate the string
in the binary file to ASCII or readable format?

I can display the others in the struct with no problem.
Just that string.


Thanks!
-ryan-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,828
Latest member
LauraCastr

Latest Threads

Top