Java Reference
In-Depth Information
type, along with the encoding (signed/unsigned, see below), determines the maximum
and minimum values that can be represented using that type.
Byte order: Are the bytes of the binary representation written to the stream (or placed in
the byte array) from left to right or right to left? If the most significant byte is transmitted
first and the least significant byte is transmitted last, that's the so-called big-endian order.
Little-endian is, of course, just the opposite.
Signed or unsigned: Signed integers are usually transmitted in two's-complement repre-
sentation. For k -bit numbers, the two's-complement encoding of the negative integer n ,
1 n 2 k 1 , is the binary value of 2 k n ; and the non-negative integer p ,0 p 2 k 1
1,
is encoded simply by the k -bit binary value of p . Thus, given k bits, two's complement can
represent values in the range 2 k 1 through 2 k 1
1, and the most significant bit (msb)
tells whether the value is positive (msb = 0) or negative (msb = 1). On the other hand, a
k -bit unsigned integer can encode values in the range 0 through 2 k 1 directly.
Consider again the itemNumber .Itisa long , so its binary representation is 64 bits (8
bytes). If its value is 12345654321 and the encoding is big-endian, the 8 bytes sent would be
(with the byte on the left transmitted first):
0
00
2
223 219 188
49
If, on the other hand, the value was sent in little-endian order, the transmitted byte values
would be:
49
188
219
223
2
0
0
0
If the sender uses big-endian when the receiver is expecting little-endian, the receiver will end
up with an itemNumber of 3583981154337816576! Most network protocols specify big-endian
byte order; in fact it is sometimes called network byte order .
Note that the most significant bit of the 64-bit binary value of 12345654321 is 0, so its
signed (two's-complement) and unsigned representations are the same. More generally, the
distinction between k -bit signed and unsigned values is irrelevant for values that lie in the
range 0 through 2 k 1
1. Unfortunately, protocols often use unsigned integers; Java's lack of
unsigned integer types means that some care is required in dealing with such values, especially
in decoding. (See program ItemQuoteDecoderBin.java in Section 3.4.2 for an example.)
As with strings, Java provides mechanisms to turn primitive integer types into sequences
of bytes and vice versa. In particular, streams that support the DataOutput interface have
methods writeShort() , writeInt() , and writeLong() , which allow those types to be written
out directly. These methods all write out the bytes of integer primitive types in big-endian byte
order using two's-complement representation. Similarly, implementations of the DataInput
interface have methods readInt() , readShort() , and so on. The next section describes some
ways to compose instances of these classes.
Search WWH ::




Custom Search