-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinaryStdOut.java
320 lines (285 loc) · 9.77 KB
/
BinaryStdOut.java
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/******************************************************************************
* Compilation: javac BinaryStdOut.java
* Execution: java BinaryStdOut
* Dependencies: none
*
* Write binary data to standard output, either one 1-bit boolean,
* one 8-bit char, one 32-bit int, one 64-bit double, one 32-bit float,
* or one 64-bit long at a time.
*
* The bytes written are not aligned.
*
******************************************************************************/
import java.io.BufferedOutputStream;
import java.io.IOException;
/**
* <i>Binary standard output</i>. This class provides methods for converting
* primtive type variables ({@code boolean}, {@code byte}, {@code char},
* {@code int}, {@code long}, {@code float}, and {@code double})
* to sequences of bits and writing them to standard output.
* Uses big-endian (most-significant byte first).
* <p>
* The client must {@code flush()} the output stream when finished writing bits.
* <p>
* The client should not intermix calls to {@code BinaryStdOut} with calls
* to {@code StdOut} or {@code System.out}; otherwise unexpected behavior
* will result.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class BinaryStdOut {
private static BufferedOutputStream out; // output stream (standard output)
private static int buffer; // 8-bit buffer of bits to write
private static int n; // number of bits remaining in buffer
private static boolean isInitialized; // has BinaryStdOut been called for first time?
// don't instantiate
private BinaryStdOut() { }
// initialize BinaryStdOut
private static void initialize() {
out = new BufferedOutputStream(System.out);
buffer = 0;
n = 0;
isInitialized = true;
}
/**
* Writes the specified bit to standard output.
*/
private static void writeBit(boolean bit) {
if (!isInitialized) initialize();
// add bit to buffer
buffer <<= 1;
if (bit) buffer |= 1;
// if buffer is full (8 bits), write out as a single byte
n++;
if (n == 8) clearBuffer();
}
/**
* Writes the 8-bit byte to standard output.
*/
private static void writeByte(int x) {
if (!isInitialized) initialize();
assert x >= 0 && x < 256;
// optimized if byte-aligned
if (n == 0) {
try {
out.write(x);
}
catch (IOException e) {
e.printStackTrace();
}
return;
}
// otherwise write one bit at a time
for (int i = 0; i < 8; i++) {
boolean bit = ((x >>> (8 - i - 1)) & 1) == 1;
writeBit(bit);
}
}
// write out any remaining bits in buffer to standard output, padding with 0s
private static void clearBuffer() {
if (!isInitialized) initialize();
if (n == 0) return;
if (n > 0) buffer <<= (8 - n);
try {
out.write(buffer);
}
catch (IOException e) {
e.printStackTrace();
}
n = 0;
buffer = 0;
}
/**
* Flushes standard output, padding 0s if number of bits written so far
* is not a multiple of 8.
*/
public static void flush() {
clearBuffer();
try {
out.flush();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Flushes and closes standard output. Once standard output is closed, you can no
* longer write bits to it.
*/
public static void close() {
flush();
try {
out.close();
isInitialized = false;
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Writes the specified bit to standard output.
* @param x the {@code boolean} to write.
*/
public static void write(boolean x) {
writeBit(x);
}
/**
* Writes the 8-bit byte to standard output.
* @param x the {@code byte} to write.
*/
public static void write(byte x) {
writeByte(x & 0xff);
}
/**
* Writes the 32-bit int to standard output.
* @param x the {@code int} to write.
*/
public static void write(int x) {
writeByte((x >>> 24) & 0xff);
writeByte((x >>> 16) & 0xff);
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
/**
* Writes the r-bit int to standard output.
* @param x the {@code int} to write.
* @param r the number of relevant bits in the char.
* @throws IllegalArgumentException if {@code r} is not between 1 and 32.
* @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.
*/
public static void write(int x, int r) {
if (r == 32) {
write(x);
return;
}
if (r < 1 || r > 32) throw new IllegalArgumentException("Illegal value for r = " + r);
if (x < 0 || x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
for (int i = 0; i < r; i++) {
boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
writeBit(bit);
}
}
/**
* Writes the 64-bit double to standard output.
* @param x the {@code double} to write.
*/
public static void write(double x) {
write(Double.doubleToRawLongBits(x));
}
/**
* Writes the 64-bit long to standard output.
* @param x the {@code long} to write.
*/
public static void write(long x) {
writeByte((int) ((x >>> 56) & 0xff));
writeByte((int) ((x >>> 48) & 0xff));
writeByte((int) ((x >>> 40) & 0xff));
writeByte((int) ((x >>> 32) & 0xff));
writeByte((int) ((x >>> 24) & 0xff));
writeByte((int) ((x >>> 16) & 0xff));
writeByte((int) ((x >>> 8) & 0xff));
writeByte((int) ((x >>> 0) & 0xff));
}
/**
* Writes the 32-bit float to standard output.
* @param x the {@code float} to write.
*/
public static void write(float x) {
write(Float.floatToRawIntBits(x));
}
/**
* Writes the 16-bit int to standard output.
* @param x the {@code short} to write.
*/
public static void write(short x) {
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
/**
* Writes the 8-bit char to standard output.
* @param x the {@code char} to write.
* @throws IllegalArgumentException if {@code x} is not betwen 0 and 255.
*/
public static void write(char x) {
if (x < 0 || x >= 256) throw new IllegalArgumentException("Illegal 8-bit char = " + x);
writeByte(x);
}
/**
* Writes the r-bit char to standard output.
* @param x the {@code char} to write.
* @param r the number of relevant bits in the char.
* @throws IllegalArgumentException if {@code r} is not between 1 and 16.
* @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.
*/
public static void write(char x, int r) {
if (r == 8) {
write(x);
return;
}
if (r < 1 || r > 16) throw new IllegalArgumentException("Illegal value for r = " + r);
if (x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
for (int i = 0; i < r; i++) {
boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
writeBit(bit);
}
}
/**
* Writes the string of 8-bit characters to standard output.
* @param s the {@code String} to write.
* @throws IllegalArgumentException if any character in the string is not
* between 0 and 255.
*/
public static void write(String s) {
for (int i = 0; i < s.length(); i++)
write(s.charAt(i));
}
/**
* Writes the string of r-bit characters to standard output.
* @param s the {@code String} to write.
* @param r the number of relevants bits in each character.
* @throws IllegalArgumentException if r is not between 1 and 16.
* @throws IllegalArgumentException if any character in the string is not
* between 0 and 2<sup>r</sup> - 1.
*/
public static void write(String s, int r) {
for (int i = 0; i < s.length(); i++)
write(s.charAt(i), r);
}
/**
* Tests the methods in this class.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
// write n integers to binary standard output
for (int i = 0; i < m; i++) {
BinaryStdOut.write(i);
}
BinaryStdOut.flush();
}
}
/******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/