Versions Compared

Key

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

...

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, 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();	
}

...

This compliant solution 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 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; , 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.

Code Block
bgColor#ccccff

public static long getInteger(DataInputStream is) throws IOException {
  return is.readInt() & 0xFFFFFFFFL; // maskMask with 32 one-bits
}

As a general principle, you should always be aware of the signedness of the data you are reading.

...

Treating unsigned data as though it were signed produces incorrect values and can lead to lost or misinterpreted data.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM03-J

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Automated Detection

Automated detection is infeasible in the general case.

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5bf26644-78fd-47f1-9e65-17ce66406b69"><ac:plain-text-body><![CDATA[

[

[API 2006

AA. References#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="4993b67c-3747-4a29-b401-1bea9d39376d"><ac:plain-text-body><![CDATA

[

[[

Harold 1997

AA. References#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="935dcd3b-b95a-4a4c-b9e5-7feb54014c3e"><ac:plain-text-body><![CDATA[

[

[Hitchens 2002

AA. References#Hitchens 02

]

]

Section 2.4.5, "Accessing Unsigned Data"

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

...


...

Image Added Image Added Ensure that division and modulo operations do not result in divide-by-zero errors      03. Numeric Types and Operations (NUM)