简体   繁体   中英

Reading unsigned bytes with RandomAccessFile

I have this method using a RandomAccessFile descriptor:

    public byte[] readByte(int number) {
        try {
            byte[] buffer = new byte[number];
            raf.read(buffer);
            return buffer;
        } catch (IOException e) {
            throw new ReadException("readBytes failed", e);
        }

    }

Which I am trying to use to read a binary file storing a series of unsigned bytes, yet I am getting negative values. Also tried with:

public byte readByte() {
    try {
        return (byte) raf.readUnsignedByte();
    } catch (IOException e) {
        throw new ReadException("readByte failed", e);
    }
}

public byte[] readByte(int number) {
    byte[] sArray = new byte[number];
    for (int i = 0; i < number; i++) {
        sArray[i] = readByte();
    }
    return sArray;
}

It seems to me that using readUnsignedByte() should return only positive values, and yet I end up with negative values all over the place.

And even forcing positive with:

public byte[] readByte(int number) {
    byte[] sArray = new byte[number];
    for (int i = 0; i < number; i++) {
        sArray[i] = (byte) (readByte() & 0xFF);
    }
    return sArray;
}

And still, I get negative values. Only way I can use positive values is then converting them when using them (I am using these numbers as an index for another array):

palette[sArray[j] & 0xFF];

What am I doing wrong?

You're casting the result of readUnsignedByte to byte - so if the result is 255 as an int (for example) it is -1 after casting to byte .

byte is always signed in Java - it always has a range of [-128, 127] . There's nothing you can do about that.

I suggest you stick with your first snippet (although use the return value from read to check that you've actually read everything you expected to), and just use the & 0xff to obtain a positive value when you need it.

An alternative is to use a short[] , but that's pretty wasteful - you're using 2 bytes of memory for every 1 byte of real data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM