Reputation: 1174
Using the solution provided here -Java input and output binary file byte size are not matching after transformation I wrote out a 2-dimensional array to disk that consists of unsigned shorts. When I checked the values of this file by reading them in I still see signed values i.e. negative values. What is the error in the code ?
fos = new FileOutputStream(destFile);
short[][] data = getData(); //defined in another class
if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN)
{
for (int i = 0;i<1200;i++)
{
for (int j = 0; j <1200;j++)
{
fos.write((data[i][j] >> 8) & 0xFF);
fos.write(data[i][j] & 0xFF);
}
}
}
else
{
for (int i = 0;i<1200;i++)
{
for (int j = 0; j <1200;j++)
{
fos.write(data[i][j] & 0xFF);
fos.write((data[i][j] >> 8) & 0xFF);
}
}
}
Upvotes: 2
Views: 240
Reputation: 111259
Java doesn't have an unsigned short datatype, but don't worry, the code works fine. The bit patterns for signed and unsigned are the same, the difference is in how the first bit is interpreted. If you ever want the unsigned value for a short you can use the AND operator:
int unsignedValue = signedShortValue & 0xFFFF;
Upvotes: 1