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.
.



Relevant Pages

  • Re: Question about sample Java application
    ... > private static String name; ... > public static void main{ ... In most of what I've been doing, when I have to do a Java ... application within that one .java file. ...
    (comp.lang.java.programmer)
  • Re: beginners question
    ... It must accept a String array as a parameter. ... public static void main ... When java tells you that it cannot find a method, ... requiring an applet viewer. ...
    (comp.lang.java)
  • JNI - unresolved _ZNSs4_Rep11_S_terminalE
    ... which (the main-driver) calls JAVA again to ... do the real work for processing the message. ... when starting the JAVA MainWrapper ... public static void main{ ...
    (comp.lang.java.programmer)
  • Re: Is conditional compiling possible in JAVA?
    ... Use boolean constants and let the compiler figure out if code can be ... many C/C++ preprocessors don't barf on Java input ... All you do is change debug to true or false and if set to false, ...
    (comp.lang.java.help)
  • wrong ELF class: ELFCLASS64 when trying to link dynamic .so library from Java/JNA
    ... I have "installed" JNA in order to be able to access native calls from ... thus I would like a Java interface). ... public static void main(Stringargs) { ...
    (comp.unix.programmer)