jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

I was just exploring the vec function but I already encountered a problem, I was not able to unpack it. Here is the code I used
#! /usr/bin/perl use strict ; use warnings ; my $bitstring = "" ; my $offset = 0 ; for my $i (0..20) { vec( $bitstring, $offset++, 4 ) = $i ; } my $bits = unpack("A4*", $bitstring); print "$bits\n" ;
From the result I realized that I do not fully understand vec and maybe also pack/unpack
so any help is appreciated!!

Thnx

LuCa

Replies are listed 'Best First'.
Re: HowTo unpack a vec (bitstring)
by Joost (Canon) on Jun 19, 2006 at 10:00 UTC
    Just to clarify: I think your main confusion is about how the C, a and A templates for (un)pack work. Observe:
    #! /usr/bin/perl use strict ; use warnings ; my $bindata = pack("CaA", 65, "B", "C"); print "$bindata\n"; print join(", ",unpack("H2H2H2",$bindata)),"\n"; print join(", ",unpack("C*",$bindata)),"\n"; print join(", ",unpack("A1A1A1",$bindata)),"\n"; print join(", ",unpack("a1a1a1",$bindata)),"\n";
Re: HowTo unpack a vec (bitstring)
by Joost (Canon) on Jun 19, 2006 at 09:13 UTC
    Erm..
    for my $i (0..20) { vec( $bitstring, $offset++, 4 ) = $i ; }
    That sets consecutive nybbles (half-bytes) to 0,1,2,3 .. etc.

    my $bits = unpack("A4*", $bitstring);
    This "unpacks" an ascii string of 4 bytes (the * at the end doesn't do anything since you didn't give a format letter). In other words, it just returns the first 4 bytes of $bitstring without converting them in any way.

    I don't think there's an unpack template for nybbles. If you want to see what you put in $bitstring, you might want to use the bit string template: "b*":

    print unpack("b*",$bitstring);
    output (broken up for readability):
    0000100001001100001010 1001101110000110010101 1101001110110111111100 0010000100110000100000
    or hex:
    print unpack("h*",$bitstring);
    output:
    0123456789abcdef012340
      Ok, I made the following changes:
      vec ($bitstring, $offset++,8) = $_ ;
      So now I can do
      my $bits = unpack("x1 C1", $bitstring);
      However I cannot do
      my $bits = unpack("x1 A1", $bitstring);
      So why is it not possible to extract an integer as an ASCII character ?

      LuCa