Skip to content
Advertisement

ByteArrayInputStream cannot read long with ByteArrayOutputStream written in Java

I have a read code for a long number like below;

ByteArrayInputStream in;
public long readUInt64() throws IOException {
    return readUInt16() | readUInt16() << 16L | readUInt16() << 32L | readUInt16() << 48L;

public int readUInt16() throws IOException {
    return readWithEOF() | readWithEOF() << 8;
}
    int readWithEOF() throws IOException {
    int data = this.in.read();
    if (data < 0)
        throw new EOFException();
    return data;
}

I have write file like below;

ByteArrayOutputStream baos;
public void writeUInt64(Long val) {
        
    writeUInt16((int) (val >> 0L));
    writeUInt16((int) (val >> 16L));
    writeUInt16((int) (val >> 32L));
    writeUInt16((int) (val >> 48L));    
}
public void writeUInt16(int num) {      
    baos.write(num >> 0);
    baos.write(num >> 8);
}

When I try to store a big value like 253402300799999L, the reading result is totally different. For small values the code runs fine. Assuming that changing read code is not possible, how can I fix this issue. thanks in advance.

Advertisement

Answer

Your reading code is incorrect.

You need to cast int to long before shift (<<).

return readUInt16() 
    | ((long)readUInt16()) << 16L 
    | ((long)readUInt16()) << 32L 
    | ((long)readUInt16()) << 48L;

So if you can’t change your read code it is impossible to fix your problem.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement