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

I have a file from which I read the first 3 bytes. The first 11 bits are irrelevant. Then I need to take remaining 13 bits. When the file is viewed in hex editor the first 3 bytes are 47 69 01 hex. Based on this the last 13 bits need to be 901 hex which is "01001 00000001" binary but I could not figure out how to do this.
my @z = unpack ("B11 B13", $buf);
gives "0000000100011" binary

I performed this operation by binary mathematics, but I can't use this as a solution because it is not flexible. I need a general solution, that will allow flexibility of choosing different offsets and field width easily. (In general I am parsing a bit aligned structure...) Thanks!

Replies are listed 'Best First'.
Re: accessing bits in a file
by BrowserUk (Patriarch) on Apr 21, 2010 at 12:18 UTC
    sub nBitsAt{ my( $n, $offset, $bits ) = @_; return unpack "x[A$offset] A$n", unpack "B*", $bits; } print nBitsAt( 13, 11, "\x47\x69\x01" );; 0100100000001
Re: accessing bits in a file
by almut (Canon) on Apr 21, 2010 at 15:05 UTC
    my $buf = "\x47\x69\x01"; print substr(unpack("B*", $buf), 11, 13); # 0100100000001
Re: accessing bits in a file
by jwkrahn (Abbot) on Apr 21, 2010 at 14:53 UTC
    $ perl -le'my $buf = "\x47\x69\x01"; print unpack "B*", substr( $buf, +-2 ) & "\x1f\xff"' 0000100100000001
Re: accessing bits in a file
by moritz (Cardinal) on Apr 21, 2010 at 12:03 UTC
    Maybe vec is helpful for you?
      Hi, I have tried to use vec, and it doesn't seem to solve my problem, since it doesn't return arbitrary number of bits at arbitrary offset. I can use any offset, but then I will get a single bit. Am I correct? I also tried to use:
      new Parse::Binary::FixedFormat [ qw(sync:b8 tei:b1 pusi:b1 tp:b1 PID:b +13) ];
      This gives me 0000000001000 in PID instead of expected 0100100000001. I wonder why? Thanks, Andrey.
        Hi, I have tried to use vec, and it doesn't seem to solve my problem, since it doesn't return arbitrary number of bits at arbitrary offset
        You can call it multiple times in a loop.
        Perl 6 - links to (nearly) everything that is Perl 6.