How do I manipulate arrays of bits?

by faq_monk (Initiate)
 on Oct 08, 1999 at 00:20 UTC Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

Use `pack()` and `unpack(),` or else `vec()` and the bitwise operations.

For example, this sets \$vec to have bit N set if \$ints[N] was set:

```    \$vec = '';
foreach(@ints) { vec(\$vec,\$_,1) = 1 }
```

And here's how, given a vector in \$vec, you can get those bits into your `@ints` array:

```    sub bitvec_to_list {
my \$vec = shift;
my @ints;
# Find null-byte density then select best algorithm
if (\$vec =~ tr/\0// / length \$vec > 0.95) {
use integer;
my \$i;
# This method is faster with mostly null-bytes
while(\$vec =~ /[^\0]/g ) {
\$i = -9 + 8 * pos \$vec;
push @ints, \$i if vec(\$vec, ++\$i, 1);
push @ints, \$i if vec(\$vec, ++\$i, 1);
push @ints, \$i if vec(\$vec, ++\$i, 1);
push @ints, \$i if vec(\$vec, ++\$i, 1);
push @ints, \$i if vec(\$vec, ++\$i, 1);
push @ints, \$i if vec(\$vec, ++\$i, 1);
push @ints, \$i if vec(\$vec, ++\$i, 1);
push @ints, \$i if vec(\$vec, ++\$i, 1);
}
} else {
# This method is a fast general algorithm
use integer;
my \$bits = unpack "b*", \$vec;
push @ints, 0 if \$bits =~ s/^(\d)// && \$1;
push @ints, pos \$bits while(\$bits =~ /1/g);
}
return \@ints;
}
```

This method gets faster the more sparse the bit vector is. (Courtesy of Tim Bunce and Winfried Koenig.)

Create A New User
Chatterbox?
 [james28909]: thanks [james28909]: what i am trying to do is track state of a chat based application. i need to be able to store the channels and such for a user, and when they join a new server/channel i need to be able to update that feild. [james28909]: do you think OO would best suite that? [karlgoethebier]: james28909: The last two are not mainstream. You have been warned ;-) [karlgoethebier]: james28909: I don't know. Try it. [james28909]: foreach server this bot is on, the gateway sends me a json response, which i parse out all the info with JSON, and this response has user information, i need to be able to add a user, and then update the user info when they join/leave rooms ect

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2017-05-25 16:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favorite model of computation is ...

Results (187 votes). Check out past polls.