Versions Compared

Key

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

...

Wiki Markup
This compliant solution reads-in an unsigned integer value into a {{long}} variable. The final value is stored in the lower 4 bytes of the {{long}} variable and the upper 4 bytes are zeroed out by and'ing with {{0xFFFFFFFF}}an array of four bytes.  The bytes are left shifted the appropriate amount and OR'ed together.  However, when the bytes are shifted they are promoted to int.  If the byte is negative, then all the left-most bits of the resulting int will be set, 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 left-most bits have to be masked off.  (cf. \[[Harold 97|AA. Java References#Harold 97]\] but the code there is wrong.)

Code Block
bgColor#ccccff
public static long readInt(InputStream 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 = 0L;
  result = (buffer[0] << 24) | (0x00FFFFFF&(buffer[1] << 16)) |
       (0x0000FFFF&(buffer[2] << 8)) | (0x000000FF&buffer[3]);
  result &= 0xFFFFFFFF0xFFFFFFFFL;
  return result;
}

Risk Assessment

...