-
Notifications
You must be signed in to change notification settings - Fork 2
/
bitstream.php
102 lines (93 loc) · 1.8 KB
/
bitstream.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
require_once 'bitarray.php';
/**
* a mechanism for writing a stream if bits into a string, which can then be easily transmistted or stored
*/
class BitStreamWriter
{
private $data = "";
private $workingByte = null;
private $cursor = 0;
/**
* initialize be creating our working byte / buffer
*/
public function __construct ()
{
$this->workingByte = new BitArray (8);
}
/**
* convert a string of zeroes and ones into a binary representation
*/
public function writeString ($bitStr)
{
for ($i = 0; $i < strlen ($bitStr); $i++)
{
$this->writeBit ((bool) $bitStr[$i]);
}
}
/**
* write a bit. 1 if $bit is true
*/
public function writeBit ($bit)
{
$this->workingByte[$this->cursor] = $bit;
$this->cursor++;
if ($this->cursor > 7)
{
$this->data .= $this->workingByte->getData ();
$this->workingByte = new BitArray(8);
$this->cursor = 0;
}
}
/**
* when the data is accessed, make sure to include any data
* byte in $this->workingByte
*/
public function getData ()
{
$data = $this->data;
if ($this->cursor > 0)
{
$data .= $this->workingByte->getData ();
}
return $data;
}
}
/**
* turns string data into a stream of bits
*/
class BitStreamReader
{
private $dataArray = null;
private $cursor = 0;
/**
* To initialize, provide string data containing the bits
*/
public function __construct ($data)
{
$this->dataArray = BitArray::load ($data);
}
/**
* read one bit at a time from the buffer, returning null for EOF
*/
public function readBit ()
{
if ($this->isEOF ())
{
return null;
}
else
{
$bit = $this->dataArray[$this->cursor];
$this->cursor++;
return $bit;
}
}
/**
* whether we've reached the end of our data
*/
public function isEOF ()
{
return !$this->dataArray->offsetExists ($this->cursor);
}
}