Java Reference
In-Depth Information
1
// BitOutputStream class: Bit-output stream wrapper class.
2
//
3
// CONSTRUCTION: with an open OutputStream.
4
//
5
// ******************PUBLIC OPERATIONS***********************
6
// void writeBit( val ) --> Write one bit (0 or 1)
7
// void writeBits( vals ) --> Write array of bits
8
// void flush( ) --> Flush buffered bits
9
// void close( ) --> Close underlying stream
10
11
public class BitOutputStream
12
{
13
public BitOutputStream( OutputStream os )
14
{ bufferPos = 0; buffer = 0; out = os; }
15
16
public void writeBit( int val ) throws IOException
17
{
18
buffer = setBit( buffer, bufferPos++, val );
19
if( bufferPos == BitUtils.BITS_PER_BYTES )
20
flush( );
21
}
22
23
public void writeBits( int [ ] val ) throws IOException
24
{
25
for( int i = 0; i < val.length; i++ )
26
writeBit( val[ i ] );
27
}
28
29
public void flush( ) throws IOException
30
{
31
if( bufferPos == 0 )
32
return;
33
out.write( buffer );
34
bufferPos = 0;
35
buffer = 0;
36
}
37
38
public void close( ) throws IOException
39
{ flush( ); out.close( ); }
40
41
private int setBit( int pack, int pos, int val )
42
{
43
if( val == 1 )
44
pack |= ( val << pos );
45
return pack;
46
}
47
48
private OutputStream out;
49
private int buffer;
50
private int bufferPos;
51
}
figure 12.15
The
BitOutputStream
class
Search WWH ::
Custom Search