in reply to Re: unpack() to several variables
in thread unpack() to several variables

I'm reading big endian integers

Replies are listed 'Best First'.
Re^3: unpack() to several variables
by Marshall (Canon) on Jul 22, 2009 at 17:05 UTC
    here is my "go at it". Its been years since I looked at pack or unpack..But I would suggest when solving a problem like this, make a binary file first that is known to be big "endian" and then work from there. My code for the unpack looks a bit strange. Fletch has some great code above. Anyway make a binary file that you know to be right, then work from there. Packing is easier than unpacking different size data things. My binary "binout" file assumes 32 bit big endian and typical character byte packing for that architecture.
    #!/usr/bin/perl -w use strict; my @x = (0x1230,0x1231,0x1232,0x1233,0x1234, 0x1235,0x1236,0x1237,0x1238,0x1239); my @c = qw (a b c d e f g h i j); open (BIN, '>', "binout") || die " unable to open binout"; binmode (BIN) || die "unable to set binmode"; print BIN pack('N'x10,@x); print BIN pack('a'x10,@c); close(BIN); open (BIN, '<', "binout") || die "CAN'T OPEN BINOUT ?!"; while(my $buff = <BIN>) { my (@tokens)= unpack ('N10C10', $buff); foreach my $digit (@tokens[0..9]) { printf "%x \n",$digit; } foreach my $char (@tokens[10..19]) { printf "%c\n", $char; } } __END__ binout is: (hex) 0000 1230 0000 1231 0000 1232 0000 1233 0000 1234 0000 1235 0000 1236 0000 1237 0000 1239 0000 1239 6162 6364 6566 6768 696a output: 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 a b c d e f g h i j