PHP5 BitArray class

Recently I had an idea to try making some kind of generative music program. I got thinking about how to model harmony and musical scales etc. It seemed like the simplest way to think of an (abstract, i.e. key-less) scale was as a 12-bit binary number.

Well, ‘the thing’ will eventually have some kind of web-facing API so I’m building it in PHP.  Some operations are conveniently done using just a binary number and bitwise operators, others (eg random access to individual bits) are less convenient and would benefit from a helper class of some kind.

I vaguely remembered reading about something called a BitArray, once upon a time, and it sounded handy. PHP doesn’t have one though. There were a couple of existing solutions, one of which is a bit broken and the other a bit too extended and specialised.

So I’ve borrowed ideas from both of them and made my own one, which is now up on Google Code: phpbitarray

Hopefully anyone interested in it can get by without docs… it is just one class which is pretty well commented.

One nice thing I learned was to implement some PHP5 built-in interfaces so that many of the usual things you can do with arrays (eg: for, foreach, count() and [] access to elements) all work as you’d expect. It also has a full complement of bitwise and set operations as methods.

Internally it stores the value as a string of ‘0101’s which I guess is not the most efficient, though it makes random access to the bits easier. If it seems worth it I’m sure some methods could be recoded so that everything was done in binary style using an integer.

4 thoughts on “PHP5 BitArray class”

  1. Thank you for this excellent bitarray class. I’ve been trying to find one that actually works, but so far none of them worked as expected. This one does. When testing if I could later add bits as needed I did run into a problem when trying to add a bit or two to an existing set because the numbering of bits goes from left to right. I’ve added the issue with example on the google code page, I suppose it’s more of a feature request to add a right-to-left way of settings bits. I’ve been trying to add it myself and I’m sure it’s something simple but just can’t get it to work.

    1. I see what you mean. You could invert the access in your own code, eg instead of doing $mybits[x] you’d do $mybits[count($mybits)-1-x]

      (hope that’s right, it’s over a year since I did any PHP…)

      Could get a bit cumbersome though. If you think that this class should always work right to left you could make the equivalent change to the class itself. Looks to me like you’d want to change…

      line #131 to:
      $this->bitString[$this->length -1 – $index] = (int)$value;

      line #169 to:
      return (bool)$this->bitString[$this->length -1 – $index];

      (I haven’t tested this… good luck!)

Leave a reply to anentropic Cancel reply