Versions Compared

Key

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

The only unsigned primitive integer type in Java is the 16-bit char data type; all of the other primitive integer types are signed. To interoperate with native languages, such as C or C++, that use unsigned types extensively, any unsigned values must be read and stored into a Java integer type that can fully represent the possible range of the unsigned data. For example, the Java long type can be used to represent all possible unsigned 32-bit integer values obtained from native code.

...

This noncompliant code example uses a generic method for reading integer data without considering the signedness of the source. It assumes that the data read is always signed and treats the most significant bit as the sign bit. When the data read is unsigned, this causes misinterpretations of the actual sign and magnitude of the values may be misinterpreted.

Code Block
bgColor#FFcccc
public static int getInteger(DataInputStream is) throws IOException {
  return is.readInt();	
}

Compliant Solution

This compliant solution assumes requires that the values read are 32-bit unsigned integers. It reads an unsigned integer value using the readInt() method. The readInt() method assumes signed values and returns a signed Java int; the return value is converted to a long with sign extension. The code uses an & operation to mask off the upper 32 - bits of the long; this produces producing a value in the range of a 32-bit unsigned integer, as intended. The mask size should be chosen to match the size of the unsigned integer values being read.

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="dbea69940ff6af83-6d17eec8-455841bf-bc5ab189-d13db8c1ff01495bb5c2b058"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

Class DataInputStream: method readInt

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d11db0b77771178c-8e7b275a-4b8b4f05-997ebb3f-fc9a7e0c24702a53ab5ac7d8"><ac:plain-text-body><![CDATA[

[[Harold 1997

AA. Bibliography#Harold 97]]

Chapter 2: , Primitive Data Types, Cross Platform Issues, Unsigned Integers

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3f36b84f4ab40a14-4746987e-4d174542-90698823-16551870b6d57221bb32fb11"><ac:plain-text-body><![CDATA[

[[Hitchens 2002

AA. Bibliography#Hitchens 02]]

2.4.5, Accessing Unsigned Data

]]></ac:plain-text-body></ac:structured-macro>

...