Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

In Java, data is stored in big-endian format (also called network order). That is, all data is represented sequentially starting from the most significant bit (MSB) to the least significant. JDK versions prior to JDK 1.4 required definition of custom methods that manage reversing byte order to maintain compatibility with little-endian systems. Correct handling of byte order related issues is critical when exchanging data in a networked environment that includes both big-endian and little-endian machines. Failure to handle byte ordering issues may can cause unexpected program behavior.

...

The read methods (readByte, readShort, readInt, readLong, readFloat and readDouble) and the corresponding write methods defined by class java.io.DataInputStream operate only on big-endian data. Use of these methods while interoperating with traditional languages, such as C or C++, is unsafe , because such languages lack any guarantees about endianness. This noncompliant code example shows such a discrepancy.

...

When programming for JDK 1.5+, use the reverseBytes() method defined in the classes Character, Short, Integer, and Long to reverse the order of the integral value's bytes. Note that classes Float and Double lack such a method.

...

Reading and writing data without considering endianness may can lead to serious misinterpretations about magnitude and sign, alike.

...

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Related Guidelines

MITRE CWE: CWE-198 "Use of Incorrect Byte Ordering"

Bibliography

Wiki Markup
\[[API 2006|AA. Bibliography#API 06]\] Class [ByteBuffer|http://download.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html]: Methods {{wrap}} and {{order}}. Class [Integer|http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html]: method {{reverseBytes}}
\[[Harold 1997|AA. Bibliography#Harold 97]\] Chapter 2: "Primitive Data Types, Cross Platform issues"
\[[MITRE 2009|AA. Bibliography#MITRE 09]\] [CWE ID 198|http://cwe.mitre.org/data/definitions/198.html] "Use of Incorrect Byte Ordering"

...

INT06-J. Avoid incorrect mixing of signed integers with bitwise operators      06. Integers (INT)      INT08-J. Provide mechanisms to handle unsigned data when required