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

Hi folks!

I have to compile a string of unknown length (more than four bytes) in which several bits have to be set.

I can use

pack 'b*', $bitmap
to create a binary string from a sequence of '0's and '1', e.g. '1100111010'

With this I just have to create my bitmap with something like:

$bitmap = '0' x 64; substr($bitmap, 0, 1) = '1'; substr($bitmap, 0, 4) = '1'; substr($bitmap, 0, 5) = '1'; substr($bitmap, 0, 14) = '1'; $binary = pack('b*', $bitmap);
This is very tedious if there are more than a handfull of bits to set.

Next problem is to check if a bit is set in a binary string.
The normal way of ANDing the string won't work because of the size of the string.

I haven't checked Math::BigInt, perhaps that is a simple solution.

Any Ideas?

Replies are listed 'Best First'.
Re: how to set bits in an arbitrary length string
by Masem (Monsignor) on Nov 14, 2001 at 20:11 UTC
    I believe you want the module Bit::Vector. Does arbitrary length bit vectors in addition to numerous other fine uses.

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    "I can see my house from here!"
    It's not what you know, but knowing how to find it if you don't know that's important

Re: how to set bits in an arbitrary length string
by blakem (Monsignor) on Nov 15, 2001 at 00:13 UTC
    First of all, I don't think those substrs are doing what you think they are.... for instance, the last one probably should be:
    # substr EXPR,OFFSET,LEN substr($bitmap,14,1) = 1;
    (or maybe 14 should be 13, but I can't tell for sure if you wanted an offset of 14 or position 14)

    Second, you can do this type bit flipping w/o the string representation with vec().

    -Blake

      You're right, was a mistake when I hacked it into the web form :-(
Re: how to set bits in an arbitrary length string
by I0 (Priest) on Nov 15, 2001 at 01:01 UTC
    (vec $binary,14,1) = 1;
Re: how to set bits in an arbitrary length string
by busunsl (Vicar) on Nov 15, 2001 at 12:13 UTC
    Thanks folks!

    I had forgotten about vec :-(.

    I need the least significant bit in the rightmost position.

    So what I use now is:

    $binary = chr(0) x 8; vec($binary, $_, 1) = 1 for (SOME, CONSTANTS); $binary = reverse $binary;