Re: MappedByteBuffer and corrupted data
On 2008-02-15 15:24 +0100, Daniele Futtorovic allegedly wrote:
On 2008-02-15 09:22 +0100, John allegedly wrote:
Hi, i've been experiencing somme corruption of data with
MappedByteBuffer. My serialisations are pretty simples. I've put
"magic" byte for the debug, and some time, the byte i read is not
equal to the "magic" value.
So i'm wondering if somebody has already experienced this kind of
troubles. If it's not a bug in Java, what can it be ?
TIA
Post a code example (sscce) if you want precise answers.
As a guess, it might be you're trying to compare signed bytes with
unsigned byte values and get entangled in promotions and widening
conversions. Careful addition of 0xFF masks might solve it.
To illustrate my point:
public static void main(String[] ss) {
int MAGIC = 0xFA;
byte b = (byte) MAGIC;
System.out.println(b == MAGIC);
System.out.println((b & 0xFF) == MAGIC);
}
Yields:
false
true
Likewise:
public static void main(String[] ss) throws Exception {
final byte MAGIC = (byte) 0xFA;
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
pos.write(MAGIC);
int read = pis.read();
System.out.println(read == MAGIC);
System.out.println(read == (MAGIC & 0xFF));
}
Yields:
false
true
Conclusion: Mind two's complement arithmetic, especially when doing IO!
In Java, bytes are signed, but the "bytes" you read off an InputStream
are unsigned.
df.