in reply to yet another "reading binary data" question
Here's probably how I would go about it:
Admittedly, fixing up the shorts is a kludge. Unfortunately, there doesn't seem to be a format for big-endian signed values, so that's why I opted for this approach. I like to use the platform-independent formats n and v for shorts as opposed to the platform-dependent formats s and S to make the code, well, platform-independent.my ($x, $y, $z, $n, $len) = ... # fill in these parameters my $format = "V$x n$y n C$z ".("Z$len" x $n); my $recsize = 4*$x + 2*$y + 2 + $z + ($n*$len); open B, '<', 'binary_file.bin' or die ...; while (read(B, $buf, $recsize) == $recsize) { my @values = unpack($format, $buf); my @x = splice(@values, 0, $x); # snip off the 4-byte ints my @y = splice(@values, 0, $y); # the 2-byte ints my $bits = splice(@values, 0, 1); my @z = splice(@values, 0, $z); # the 1-byte ints # @values now contain just the null-terminated strings # manually fix up signed vs. unsigned shorts in @y: $y[1] -= 65536 if ($y[1] > 32767); # repeat for each signed valued ...process the record... }
Update: Fixed format based on alexm's comment.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: yet another "reading binary data" question
by alexm (Chaplain) on May 07, 2008 at 19:46 UTC | |
by pc88mxer (Vicar) on May 07, 2008 at 23:02 UTC | |
|
Re^2: yet another "reading binary data" question
by dwalin (Monk) on May 07, 2008 at 19:37 UTC |