1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.archive.io;
24
25
26 import java.io.EOFException;
27 import java.io.IOException;
28 import java.io.InputStream;
29
30
31 /***
32 * Reads integers stored in big or little endian streams.
33 *
34 * @author pjack
35 */
36 public class Endian {
37
38
39 /***
40 * Static utility class.
41 */
42 private Endian() {
43 }
44
45
46 /***
47 * Reads the next little-endian unsigned 16 bit integer from the
48 * given stream.
49 *
50 * @param input the input stream to read from
51 * @return the next 16-bit little-endian integer
52 * @throws IOException if an IO error occurs
53 */
54 public static char littleChar(InputStream input) throws IOException {
55 int lo = input.read();
56 if (lo < 0) {
57 throw new EOFException();
58 }
59 int hi = input.read();
60 if (hi < 0) {
61 throw new EOFException();
62 }
63 return (char)((hi << 8) | lo);
64 }
65
66
67 /***
68 * Reads the next little-endian signed 16-bit integer from the
69 * given stream.
70 *
71 * @param input the input stream to read from
72 * @return the next 16-bit little-endian integer
73 * @throws IOException if an IO error occurs
74 */
75 public static short littleShort(InputStream input) throws IOException {
76 return (short)littleChar(input);
77 }
78
79
80 /***
81 * Reads the next little-endian signed 32-bit integer from the
82 * given stream.
83 *
84 * @param input the input stream to read from
85 * @return the next 32-bit little-endian integer
86 * @throws IOException if an IO error occurs
87 */
88 public static int littleInt(InputStream input) throws IOException {
89 char lo = littleChar(input);
90 char hi = littleChar(input);
91 return (hi << 16) | lo;
92 }
93
94
95 /***
96 * Reads the next big-endian unsigned 16 bit integer from the
97 * given stream.
98 *
99 * @param input the input stream to read from
100 * @return the next 16-bit big-endian integer
101 * @throws IOException if an IO error occurs
102 */
103 public static char bigChar(InputStream input) throws IOException {
104 int hi = input.read();
105 if (hi < 0) {
106 throw new EOFException();
107 }
108 int lo = input.read();
109 if (lo < 0) {
110 throw new EOFException();
111 }
112 return (char)((hi << 8) | lo);
113 }
114
115
116 /***
117 * Reads the next big-endian signed 32-bit integer from the
118 * given stream.
119 *
120 * @param input the input stream to read from
121 * @return the next 32-bit big-endian integer
122 * @throws IOException if an IO error occurs
123 */
124 public static int bigInt(InputStream input) throws IOException {
125 char hi = bigChar(input);
126 char lo = bigChar(input);
127 return (hi << 16) | lo;
128 }
129 }