[Israel.pm] pack vs. different architectures

Offer Kaye offer.kaye at gmail.com
Mon Feb 21 23:45:50 PST 2005


On Tue, 1 Feb 2005 14:29:19 +0200, Roman M. Parparov
<romm at empire.tau.ac.il> wrote:
> Hey, guys.
> 
> I am facing the following problem:
> I have to write a C structure into a binary file using a perl program.
> That file is later read by an external utility.
> The perl program runs on an Origin200 (IRIX64 nasa 6.4 02121744 IP27 mips)
> compiled using 'cc -32' (because of Oracle 7.3.4 present) - perl 5.8.5
> The external utility runs on a Pentium (Linux earth 2.4.22 i686)
> 
> Please note that the irix is a 64-bit machine.
> 
> The structure is as following:
> struct rpthdr {
>   char  id[8];    /* Station ID */
>   float lat;      /* Latitude of Station */
>   float lon;      /* Longitude of Station */
>   float t;        /* Time in grid-relative units */
>   int   nlev;     /* Number of levels following */
>   int   flag;     /* Level independent var set flag */
> } hdr;
> 
> I am trying to write it using the following:
>         open(DAT,">$dat");
>         binmode(DAT,':raw');
>         $hdr = {
>                 id=>'RSlifkin',
>                 lat=>30.5,
>                 lon=>31.5,
>                 t=>0,
>                 nlev=>1,
>                 flag=>1,
>                 },
> 
>         my $str =
>           pack('Z9',$hdr->{id}) .
>             pack('f',$hdr->{lat}) .
>               pack('f',$hdr->{lon}) .
>                 pack('f',$hdr->{t}) .
>                   pack('I',$hdr->{nlev}) .
>                     pack('I',$hdr->{flag});
>         syswrite(DAT,$str);
> 
> After this I need to write a sequence of numbers:
>         for my $d (@data) {
>             syswrite(DAT,pack('f',$d));
>         }
> In fact I am writing a sequence of such structures.
> 
> But I am still having problems reading the file afterwards with that
> external utility! For example, if I pack the id string with Z8, I lose
> the last character, and if I pack it with a8 - two additional characters
> are read for some reason. The lat/lon fields are read incorrectly and the
> second structure is already a total garbage.
> 
> I guess given these architectures, the packing must be less trivial...
> Any advices?
> 

Did you ever solve this? 
I'm asking because I just stumbled on:
http://search.cpan.org/dist/Convert-Binary-C/
and it seems to be just what the doctor ordered :-)

-- 
Offer Kaye



More information about the Perl mailing list