[Chicago-talk] Parsing a Hex file
lembark at wrkhors.com
Fri Jan 19 15:09:44 PST 2007
Jay Strauss wrote:
> Ok I'm feeling slow,
> I have:
> (Hex): 01 00 08 30 37 30 31 31 32 30 30
> so its field 1 (first 2 bytes)
> length 8, (3rd field)
> value: 07011200 (i.e hex 30 37 30 31 31 32 30 30)
> But I can't get the unpack correct (with the proper data types):
> my ($field_num, $value) = unpack("S2, S/A*", $file_contents);
> my $value is never correct. Could someone point out my error?
If you know that the value following is 8 bytes long then
specify it as 8 bytes in the format and validate that you
have what you wanted (e.g., there should be some sort of
an end-of-record mark in the data). At that point you can
read it via
You can read 8 byts into a char via:
though you may get bit by UTF8 or ASCII values in the string
depending on how the IO is set up.
read or sysread would help in that case since they don't
put any extra layers between you and the data (I think?).
You might do better with:
my( $field, $size ) = unpack 'S2 S', $buffer;
# some sort of sanity checks...
die "Bogus field: out of sequence" unless $field == ++$last_field;
die "Offball size: '$size'" unless 0 < $size && $size < 100;
my ( undef, $value ) = unpack "x3 A$size", $buffer;
substr $buffer, 0, $size + 3, '';
i.e., read and validate the size first three bytes and
then use the size to slurp some more from the buffer.
Double-check me on the best way to ignore a set of bytes.
Steven Lembark 85-09 90th Street
Workhorse Computing Woodhaven, NY 11421
lembark at wrkhors.com +1 888 359 3508
More information about the Chicago-talk