...
| Code Block | ||
|---|---|---|
| ||
DataInputStream dis = new DataInputStream(
new FileInputStream("data.txt")); // Little-endian data might be read as big-endian
int serialNumber = dis.readInt();
|
Compliant Solution
...
This compliant solution wraps the byte array containing the integer bytes read-in into a ByteBuffer and sets the byte order to little-endian. The result is stored in the integer serialNumber.
| Code Block | ||
|---|---|---|
| ||
DataInputStream dis = new DataInputStream(
new FileInputStream("data.txt"));
byte[] buffer= new byte[4];
int bytesRead = dis.read(buffer); // Bytes are read into buffer
int serialNumber = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
|
Compliant Solution
...
Assuming that an integer value is to be read from the file, read and write methods can be defined for handling little-endian data. The readLittleEndianInteger method reads data into a byte buffer and then pieces together the integer in the right order. Long values can be handled by defining a byte buffer of size 8. The writeLittleEndianInteger method obtains bytes by repeatedly casting the integer so that the most significant byte is extracted on successive right shifts.
| Code Block | ||
|---|---|---|
| ||
// read method
public static int readLittleEndianInteger(InputStream ips) throws IOException {
int result;
byte[] buffer = new byte[4];
int check = ips.read(buffer);
if (check != 4) throw new IOException("Unexpected End of Stream");
result = (buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0];
return result;
}
// write method
public static void writeLittleEndianInteger(int i, OutputStream ops) throws IOException {
int result;
byte[] buffer = new byte[4];
buffer[0] = (byte) i;
buffer[1] = (byte) (i >> 8);
buffer[2] = (byte) (i >> 16);
buffer[3] = (byte) (i >> 24);
ops.write(buffer);
}
|
Compliant Solution
...
In JDK 1.5+, the Integer.reverseBytes() method can be used to reverse the order of the bytes constituting the integer. Note that there is no such method for float and double values.
...