Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: updated CS

...

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

Compliant Solution

Wiki MarkupThis compliant solution assumes that the unsigned integer has 32 bits. It reads in an unsigned integer value into an array of four bytes. The bytes are left shifted by the appropriate amount and OR'ed together. However, when the bytes are shifted they are promoted to {{int}} (the last byte is promoted to an {{int}} to compute the bitwise-OR). If the byte is negative, then all the higher order bits of the resulting {{int}} will be set due to sign extension, and these have to be masked off. Finally, the whole {{int}} expression may be negative when it is promoted to the {{long}} {{result}} and, again, the higher order bits have to be masked off. (cf. \[[Harold 97|AA. Java References#Harold 97]\] but the code there is incorrect)into a long variable using the readInt() method. If the read integer is unsigned, the most significant bit may be turned on. Consequently, all the higher order bits of the resulting long will be set due to sign extension, and these have to be masked off as demonstrated.

Code Block
bgColor#ccccff
public static long readIntgetInteger2(InputStreamDataInputStream is) throws IOException {
  byte[] buffer = new byte[4];
  int check = is.read(buffer);
  if (check != 4) throw new IOException("Unexpected End of Stream!");
  long result = (buffer[0] << 24) | (0x00FFFFFF&(buffer[1] << 16)) |
       (0x0000FFFF&(buffer[2] << 8)) | (0x000000FF&buffer[3]);
  result &= 0xFFFFFFFFL;
  return result;return is.readInt() & 0xFFFFFFFFL;	
}

Risk Assessment

Treating an unsigned type as signed can result in misinterpretations and can lead to erroneous calculations.

...