Alasdair
Alasdair

Reputation: 14113

Checking whether a bit is 1 or 0 in PHP

How do I check whether a bit is 1 or 0 in PHP?

I need to loop through a large file and check each bit, whether it is 1 or 0 and put this into a multi-dimentional array based on a set "column length".

Something like:

$binary = 0100110110110001100010001111101100111;
$binary=binaryToArray($binary,10);

And the result would look like:

array[0][0]=0; array[0][1]=1; array[0][2]=0; //etc.
array[1][0]=1; array[1][1]=1; array[1][2]=0; //etc.

Upvotes: 1

Views: 173

Answers (1)

Artefacto
Artefacto

Reputation: 97835

You can write a class that wraps the data and returns an instance of another class that wraps the byte:

class DataBitAccessor implements ArrayAccess {
    private $data;
    public __construct($data) {
        $this->data = $data;
    }

    public offsetExists($offset) {
        return is_int($offset) &&
                $offset >= 0 && $offset < strlen($this->data);
    }
    public offsetGet($offset) {
        if (!$this->offsetExists($offset)) {
            return null;
        }
        return new Byte($this->data{$offset});
    }
    public offsetSet($offset, $value) {
        throw new LogicException();
    }
    public offsetUnset($offset) {
        throw new LogicException();
    }
}

class Byte implements ArrayAccess {
    private $byte;
    public __construct($byte) { $this->byte = ord($byte); }
    public offsetExists($offset) {
        return is_int($offset) &&
                $offset >= 0 && $offset < 8;
    }
    public offsetGet($offset) {
        if (!$this->offsetExists($offset)) {
            return null;
        }
        return ($this->byte >> $offset) & 0x1;
    }
    public offsetSet($offset, $value) {
        throw new LogicException();
    }
    public offsetUnset($offset) {
        throw new LogicException();
    }
}

(untested)

You can also return a string directly from DataBitAccessor

return str_pad(base_convert(
        ord($this->data[$offset]), 10, 2), 8, "0", STR_PAD_LEFT);

Upvotes: 2

Related Questions