Reading and Writing Integers

The DataOutputStream class has methods for writing all of Java’s primitive integer data types: byte, short, int, and long. The DataInputStream class has methods to read these types. It also has methods for reading two integer data types not directly supported by Java or the DataOutputStream class: the unsigned byte and the unsigned int.

Integer Formats

While Java’s platform independence guarantees that you don’t have to worry about precise data formats when working exclusively in Java, you frequently need to read data created by a program written in another language. Similarly, it’s not unusual to have to write data that will be read by a program written in a different language. For example, most Java network clients (like HotJava) talk primarily to servers written in other languages, and most Java network servers (like the Java Web Server) talk primarily to clients written in other languages. You cannot naively assume that the data format Java uses is the data format other programs will understand; you must take care to understand and recognize the data formats being used.

Although other schemes are possible, almost all modern computers have standardized on binary arithmetic performed on integers composed of an integral number of bytes. Furthermore, they’ve standardized on two’s complement arithmetic for signed numbers. In two’s complement arithmetic, the most significant bit is 1 for a negative number and for a positive number; the absolute value of ...

Get Java I/O now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.