data = $data; } public function skip(int $numBytes): bool { if ($numBytes < 0 || $numBytes > strlen($this->data)) return false; $this->offset += $numBytes; return $true; } public function seek(int $pos): bool { if ($pos < 0 || $pos > strlen($this->data)) return false; $this->offset = $pos; return true; } public function read(int $numBytes, bool $str = true){ $bytes = null; for ($i = $this->offset; $i < $this->offset + $numBytes; $i++) { $str ? $bytes .= $this->data[$i] : $bytes[] = $this->data[$i]; } return unpack('H*', $bytes); } public function rewind() : bool { $this->offset = 0; return true; } public function write8(int $offset, int $byte){ $this->data[$offset] = pack('C', $byte); } public function writeBytes(int $offset, string $bytes){ if ($offset < 0 || $offset > strlen($this->data) || $bytes == '') return false; $_bytes = str_split($bytes, 2); foreach($_bytes as $k => $byte){ $pos = $offset + $k; $this->data[$pos] = pack('H*', $byte); } } public function getData(){ return $this->data ? $this->data : false; } public function getOffset(): int { return $this->offset; } /* @return Byte with Nth bit set to X */ public function setBit(int $byte, int $pos, bool $bit){ return ($bit ? ($byte | (1 << $pos)) : ($byte & ~(1 << $pos)) ); } /* @return Bit at Nth position in Byte */ public function getBit(int $byte, int $pos) : int { return intval(($byte & (1 << $pos)) != 0); } } $c = new D2ByteReader($data); $c->seek(12); $checksum = $c->read(4); var_dump($checksum); $c->write8(12, 0xFF); $checksum = $c->read(4); var_dump($checksum); $c->writeBytes(12, "FFC0FDA1"); // invalid checksum, but just testing write. Works! $checksum = $c->read(4); var_dump($checksum); $c->writeBytes(12, "b5bc59b3"); // Valid checksum, but just testing write. Works! $checksum = $c->read(4); var_dump($checksum); /* Barely any binary functions, all string manipulation on binary files. Working! To just modify bits in an aligned byte, use setBit(); To just get which bit is set in a byte, use getBit(); To read X arbitary unaligned bits in bytes, Seek to offset, Read X bytes, Convert X bytes to bits, Reverse bit order in each byte Load D2BitReader, Modify nth Bit, Return all bits Convert to bytes Reverse bit order in byte Save bytes function setBit(int $n, int $p, bool $b){ return ($b ? ($n | (1 << $p)) : ($n & ~(1 << $p)) ); } function getBit(int $b, int $p){ return intval(($b & (1 << $p)) != 0); } */